简体   繁体   中英

Can someone explain how useEffect works in detail?

Especially the part when we provide an empty array of dependencies to the useEffect. Because to my knowledge, there is an effect with every render. But how does next useEffect knows that it has to run exactly one time?

But how does next useEffect knows that it has to run exactly one time?

Because when you specify a dependency array, the effect hook only calls the callback:

  1. On mount, and

  2. If something in the array changes

An empty array is an empty array; nothing in it ever changes. So the callback is only run once, on mount, and never again.

Because to my knowledge, there is an effect with every render.

I'm not sure what you mean by "effect" there, but if you're using "effect" in the way useEffect does, then no, there isn't, not if you supply an array as the second argument to useEffect. If you don't supply an array, then the effect hook will call the callback after each call to the component function. But with an array, it only does so on mount and when something changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM