0

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 <>...</>
}

1 Answer 1

1

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.

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

Comments

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.