Middle
Why does setState not update the value immediately? What is batching?
sobes.tech AI
Answer from AI
In React, setState does not update the state immediately because state updates can be asynchronous and batched together for performance optimization.
Why does this happen:
- React groups multiple
setStatecalls into one to avoid unnecessary re-renders. - State updates are queued and applied together, followed by a single re-render.
What is batching:
- It is the process of combining multiple state updates and effects into one operation.
- It helps improve performance by reducing the number of re-renders.
Example:
function Counter() {
const [count, setCount] = React.useState(0);
function handleClick() {
setCount(count + 1);
setCount(count + 2);
// Both calls will be batched, and the final value will be count + 2, not count + 3
}
return <button onClick={handleClick}>{count}</button>;
}
To get the current state during multiple updates, use the functional form of the updater:
setCount(prevCount => prevCount + 1);
setCount(prevCount => prevCount + 2);
Thus, batching is an optimization mechanism that makes state updates more efficient but requires understanding the asynchronous nature of setState.