Lets say we have two nested components. Both of them has useEffects. Now if we run the app. the child useEffect is executed first and after that its parent components useEffect is executed.
As far as I know this architecture is for adapting better performance. But I don’t know how it is done.
2
Answers
If you look at react class based components:
ComponentDidMount()
is invoked immediately after a component is mounted, but thecomponentDidMount()
method of child components is invoked before that of parent components.Hence the useEffect() for child component triggers before the parent component.
In React, when a component is rendered that contains child components, the rendering process starts from the top of the component tree (root) and progresses down to the leaf nodes. As React traverses the tree, it comes across any useEffect hooks and places them in a queue to be executed after the rendering is completed.
If React encounters a child component while rendering a parent component, it will prioritize rendering the child component first, including executing any useEffect hooks within it. Once the child component is fully rendered and its associated effects are executed, React proceeds with rendering the parent component. The useEffect hooks within the parent component are then added to the execution queue and processed accordingly.
cc:https://react.dev/reference/react/useEffect