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

后端 未结 2 799
甜味超标
甜味超标 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:15

    if you want useEffect to behave like the componentDidMount() just pass the [] as the second argument after the callback argument.

    useEffect(()=>{
    // this we executed once the component is mounted (mimic the componentDidMount)
    },[])
    

    so the useEffect introduced instead of using componentDidMount or componentDidUpdate so in the cases above when you reload it behaves like componentDidMount and on the second case when the component already mounted and you navigated back it behaves like componentDidUpdate.

    if you are serious about the console log's for that I would say the useEffect calls the callback(first argument) in Asynchronous matter

    from the react doc

    Unlike componentDidMount or componentDidUpdate, effects scheduled with useEffect don’t block the browser from updating the screen. This makes your app feel more responsive. The majority of effects don’t need to happen synchronously.

提交回复
热议问题