Sub topic 5
State is a snapshot for each render
This chapter assumes you can declare state with useState and call a setter from an event handler. It explains what value your code sees after you call the setter.
One render, one fixed value
React calls your component function once per render. In that call, count is a plain constant. It does not change while the render's code and handlers run. Calling setCount does not edit that constant. It asks React to run the component again, and that new call gets a new count.
Each render therefore works like a photograph of state. Every handler created in that render keeps the photograph it was created with.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log('right after set:', count);
setTimeout(() => {
console.log('one second later:', count);
}, 1000);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}On the first click, count is 0. The button changes to "Clicked 1 times". The console still prints 0 twice, once right away and once after a second. Both logs run inside the handler from the first render, and that handler only knows the value 0.
The classic surprise
The same rule explains why repeated updates can seem to be ignored.
function addThreeWrong() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}When count is 0, this is the same as setCount(1) three times. The final state is 1, not 3. Each line computes its argument from the same snapshot.
Common errors
- Logging state after the setter and concluding the update failed. The update is scheduled, and the log shows the current snapshot.
- Expecting a delayed callback, such as a
setTimeoutor an async function, to see newer state. It sees the snapshot from the render that created it. - Writing
setCount(count + 1)several times in a row and expecting more than one increment.
A snapshot is also predictable. If you know which render a handler came from, you know exactly which values it can read.
The next chapter shows how updater functions, such as setCount(c => c + 1), let you build on the latest pending value instead of the snapshot.
Exercise
In a component where count is 5, a handler runs setCount(count + 2); setCount(count + 10); alert(count);. What does the alert show, and what is count in the next render?
Show answer
The alert shows 5, because the handler reads the snapshot from the current render. The next render has count equal to 15. React processes the queued updates in order, so the second call (count + 10, which is 15) replaces the first result (7).