Should I rely on the dependency list check of react useEffect hook?

349 views Asked by At

Consider the following code

useEffect(effect, [v]) // v can be undefined

I want to run the effect function only after the first render or when v changes.

My questions are

  1. Do I need to check whether v changes in effect? Or I can rely on react to check the value of the dependency list (i.e., the [v]).
  2. If the answer of 1. is the latter, is this behavior supposed to be changed in the near future? For e.g., when the concurrent mode is released.

From react official docs

Conditionally firing an effect

The default behavior for effects is to fire the effect after every completed render. That way an effect is always recreated if one of its dependencies changes.

It says if one of its dependencies changes, then, an effect is recreated. However, it does not mention the reverse: an effect is recreated if and only if one of its dependencies changes.

I only remember that in the early stage of hook, I read somewhere that the effect function can be run in some cases even without v's change, in order to optimize the memory, or in concurrent mode?? I really do not remember exactly and could not find out the source.

It would be very helpful if anyone can tell me how exactly React does, or refer to the related internal source code of react. I think they would have a special check of the first render, otherwise, when v is undefined after the first render, effect will not run.

1

There are 1 answers

0
Sang On

I also posted the question on react repo here. The thread helped me solved my question.

Hope that it also helps others.