Why does the state variable show the old value right after calling setState?
State is a snapshot for the current render. Calling the setter only schedules the next render; the variable in the running function does not change. React also batches several updates in one event into a single render.
Explain it simply
Think of a printed exam paper. If you change an answer in your head, the paper in your hand still shows the old one until a new paper is printed. Each render is one printed paper: every variable in it is fixed.
The setter asks React to print a new paper later. React waits until the handler finishes, then renders once with all the updates combined. That is batching.
Example
function Counter() {
const [n, setN] = useState(0);
function handle() {
setN(n + 1);
setN(n + 1);
console.log(n); // still 0
}
// after one click, n is 1 (both calls used n = 0)
function handleFixed() {
setN(prev => prev + 1);
setN(prev => prev + 1); // after one click, n is 2
}
return <button onClick={handleFixed}>{n}</button>;
}What to say in the interview
"State behaves like a snapshot per render. The setter does not change the variable in the current closure, it queues an update, and React batches updates from one event into one render. If the next value depends on the previous one, I use the updater form, setN(prev => prev + 1), so queued updates build on each other."
Common mistakes
- Reading state right after setting it and expecting the new value.
- Calling setN(n + 1) twice and expecting +2.