Search code examples
reactjsdependenciesuse-effect

Directly using several states included in useEffect's dependency array


Considering an useEffect with 2 different states in the dependency array. The useEffect hook will run whenever any of those two states are updated, but if i update one of them, will i have access to the lastest value of the other inside useEffect? And if not, what is the best approach to it?

function Component() {
  const [state1, setState1] = useState('');
  const [state2, setState2] = useState('');

  useEffect(() => {
    console.log(state1, state2)
  }, [state1, state2]);
  
  return <>...</>
}

Solution

  • The callback inside useEffect will run after the render conditionally based on dependency array. If your state values are updated in the same render cycle then they are batched (by React) and the next render cycle will show both the correct values in the useEffect callback.

    If you only update any one of them, you do not have to worry about the other value because the callback in useEffect will be using the recently updated value of the other variable too.

    Note: The only time you might face an issue is when you have stale state values because of closure, but that is a specific case.