In useEffect, what's the difference between providing no dependency array and an empty one?

后端 未结 1 704
说谎
说谎 2020-12-24 08:29

I gather that the useEffect Hook is run after every render, if provided with an empty dependency array:

u         


        
相关标签:
1条回答
  • 2020-12-24 08:53

    It's not quite the same.

    • Giving it an empty array acts like componentDidMount as in, it only runs once.

    • Giving it no second argument acts as both componentDidMount and componentDidUpdate, as in it runs first on mount and then on every re-render.

    • Giving it an array as second argument with any value inside, eg , [variable1] will only execute the code inside your useEffect hook ONCE on mount, as well as whenever that particular variable (variable1) changes.

    You can read more about the second argument as well as more on how hooks actually work on the official docs at https://reactjs.org/docs/hooks-effect.html

    0 讨论(0)
提交回复
热议问题