0

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.

4
  • useeffect with a data as second argument will call the functions inside of it whenever given data has changed since the previous one, now if you use two useEffects each one will call the defined functions according to data, try to log something in useeffects and change the data in the app to get better idea Commented Feb 2, 2021 at 18:00
  • I know this basic info about dependency array Commented Feb 2, 2021 at 18:02
  • if you know why are you asking? Commented Feb 2, 2021 at 18:02
  • please see answer below Commented Feb 2, 2021 at 18:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

perfect, exactly was I was missing. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.