Why Doesn’t React Show the New State Immediately After setState?

Asked 1 hour ago 9 views

0

I’m trying to understand a behavior I keep running into in a React component: after calling a state setter, logging the state on the next line still prints the old value.

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1); // Requests an update using the current render's count.
    console.log(count);  // Still reads the value captured by this render.
  }

  return <button onClick={handleClick}>{count}</button>;
}

Is this mainly because React batches updates, or because the handler keeps a snapshot of the state from the render where it was created? I’d also like to know when a functional update is the better choice, especially if several updates can happen in quick succession.

0 Answers


Write Your Answer