0

I am trying to understand why the useEffect of a children component gets called before the Parent component useEffect.

From my understanding, useEffect shoulde be called in the order they are defined based on React's documentation:

React will apply every effect used by the component, in the order they were specified.

This would mean, a Parent's useEffect should be called before a Children's useEffect, but this is not the case.

Example:

const MainComponent = () => { return { <ParentComponent /> } const ParentComponent = () => { useEffect(() => { console.log('parent'); }, []); return <div>Parent <ChildrenComponent /></div>; } const ChildrenComponent = () => { useEffect(() => { console.log('children'); }, []); return <div>Children</div>; } 

If you check the console, you should see first children and then parent

Live Code: https://codesandbox.io/s/crazy-butterfly-yn046?file=/src/App.js

My gut tells me this has to do with how react does Layout and Paint of the Parent-Children components?

2

1 Answer 1

1

This:

React will apply every effect used by the component, in the order they were specified.

Would be more precisely stated as:

React will apply every effect used by the component, in the order they were specified in that component.

For example:

const SomeComponent = () => { useEffect(() => { console.log('This will run first'); }); useEffect(() => { console.log('This will run second'); }); // ... 

is guaranteed to run in order.

It's not saying anything about the order that effects in different components run.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.