u9kV-6J
u9kV-6J

Reputation: 48

Clarification on useEffect dependency array

I'm trying to understand the React (functional) component lifecycle little better and I'm getting confused by useEffect() when it is given a dependency array as second argument. I've read the docs and I feel like I understand the basics of useEffect and its second argument but still would like to know a little more.

For example

A component has two state variables: stateVarA and stateVarB.

setStateVarA() is called, component returns...render runs...reconciliation happens... there was some kind of a change so DOM is updated.

Now, this is where i get confused. If we had two useEffect(), one with [stateVarA] dependency array and another one with [stateVarB] dependency array, how does React 'know' which state variable was responsible for the latest update (since, in this case, only the useEffect(f(),[stateVarA]) will run)? is this information stored somewhere in the state object? I feel like I'm missing something basic here.

Upvotes: 0

Views: 272

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370669

For each useEffect in the component, it will go through each item of the dependency array. If one of the items is different (or if this is the initial render), that effect will run.

When an effect runs, the associated dependency array is stored in React's internals. For example, given

useEffect(() => {
  // do stuff
}, [foo, bar]);

Let's say that both variables are 1 on initial render. Then, the dependency array associated with this effect is saved as

[1, 1]

On subsequent renders, [foo, bar] is evaluated again, and compared to the prior dependency array. When there are changes, the new dependency array values replaced the old one in React internals, and the effect callback runs.

For example, bar might change to 2, resulting in

[1, 2]

and the callback will run, and React will update the "current dependency array values" for that effect to [1, 2]. These current values are not stored in state - they're internal to useEffect's implementation.

Upvotes: 1

Related Questions