function handleClick() {
setCount(count + 1);
console.log(count); // still the old value
setCount(c => c + 1); // applied to the queued value
}
State is a snapshot because each render sees fixed state values. Setting state does not change the variable you already have. It asks React to render again with a new value.
Each render is a function call that receives the state values for that render. Event handlers and effects created during that render close over those values. That means they remember the values from the render that created them.
This has two effects:
setCount(count + 1); console.log(count);logs the old value.- Calling
setCount(count + 1)three times in one handler adds only one. Each call computes from the same snapshot, so each one sets0 + 1.
When the next state depends on the previous one, pass an updater function: setCount(c => c + 1). React queues updaters and applies them in order to the latest pending state. If you need the new value right away, compute it into a local variable and use that variable.
- State is fixed for a given render. Setters schedule a new render.
- Handlers remember the values from the render that created them.
- Reading state right after setting it gives the old value.
- Use the updater form
setX(prev => ...)when the update depends on the previous state. - React batches updates and processes them before the next render.