What is the correct order of execution of useEffect in React parent and child components?

后端 未结 2 797
甜味超标
甜味超标 2021-02-15 13:17

For example, if I have components A and B, and component B is the child of component A:


  

Inside A we have:

2条回答
  •  無奈伤痛
    2021-02-15 14:12

    Ok I will try to clear your confusion. If you have some components like this

    
     
    
    

    Then on the first load (Reload) log will be

    Child B useEffect

    Parent A useEffect

    Then lets say you navigate to some route and then go to Child component log will be

    Child B useEffect

    Parent useEffect won't be called.

    As react doc says

    you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

    So all of these lifecycle methods are called after the component is mounted and when component is mounted the child components inside that component have already been mounted and their lifeCycle have been called already

    Sandbox to give you an idea how useEffect is called, it has Roster as Parent and Schedule as child. if you navigate to Header and come back to Schedule only it's useEffect is called.

    In your case maybe Parent useEffect is being called when you navigate to child component but that is because of some other reason maybe you have some callback that sets Parent state and thus cause it's useEffect to be called, but we are talking about how useEffect works in general case

    Hope it helps

提交回复
热议问题