reactjs / reactjs/react.dev

[Suggestion]: Adding documentation to note that Effects in children components are committed before their parent component

Open
#7,748 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type: documentation
Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

Summary

Adding documentation to the useEffect page to note that Effects in children components are committed before their parent component

Page

https://react.dev/reference/react/useEffect

Details

Hi

I was digging into React internals and learning how it works under the hood. I came across an interesting behaviour in Effects -- where the Effects in children components are committed before their parent component.

For example:

function Parent({ children }) {
  useEffect(() => {
    console.log("Parent committed effect");
  }, []);

  return <div>{children}</div>;
}

function Child() {
  useEffect(() => {
    console.log("Child committed effect");
  }, []);

  return <p>Child</p>;
}

export default function App() {
  return (
      <Parent>
        <Child />
      </Parent>
  );
}

The result in the console will be

Child committed effect
Parent committed effect

(I made a small animation describing the traversal)

Image

I understand that it is due to how React traverses the Fiber tree during the Commit phase (recursivelyTraversePassiveMountEffects), but it seems like it does confuse some people in

This is not a bug, but I think it would be helpful to have this documented, perhaps in the Caveats or the Troubleshooting section to avoid confusion around this "unexpected behaviour".

What do you think? :)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the useEffect reference page, especially its Caveats and Troubleshooting sections, then review the linked ReactFiberCommitWork.js traversal for context. Done means the page clearly documents that child Effects are committed before parent Effects, using the reported example and avoiding any implication that this behavior is a bug.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
50/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.