Sub topic 5
State is a snapshot for each render
This chapter assumes you can write a function component, call useState, and attach an onClick handler. It also assumes you are comfortable with closures. If you have seen a handler log a "stale" value, this chapter explains why.
State does not change inside a running function
React calls your component function once per render. In that call, useState returns the state value for that render, and the value stays fixed until the function returns. Calling a setter does not modify the variable you already destructured. It asks React to run the component again with a new value.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
console.log('before:', count);
setCount(count + 1);
console.log('after:', count);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}On the first click, both lines log 0. The button then shows 1, because React rendered again after the handler finished. In that second render, count is a new constant whose value is 1.
Each render is a snapshot. It has its own props, its own state values, and its own handler functions. Those handlers close over that render's values.
What happens on a click
The sequence below shows one click. Notice that the handler belongs to render 1 and keeps seeing render 1's value.
Closures keep the old value alive
The snapshot rule explains a common surprise with delayed code.
import { useState } from 'react';
function DelayedAlert() {
const [message, setMessage] = useState('Hello');
function handleSend() {
setTimeout(() => {
alert(`Message at click time: ${message}`);
}, 3000);
}
return (
<>
<input value={message} onChange={e => setMessage(e.target.value)} />
<button onClick={handleSend}>Send in 3 seconds</button>
</>
);
}Click the button, then edit the input before the three seconds pass. The alert still shows the text from the moment of the click. The timeout callback was created during the render in which you clicked, so it closed over that render's message. The input shows newer text because newer renders happened. The callback belongs to the old one.
This is not a bug in React. It is the same closure behavior that JavaScript gives any function. State follows the rule because each render's variables are constants.
Reading the same value several times
Because count does not change during a handler, repeating the same expression repeats the same result.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function addThree() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
return (
<>
<p>{count}</p>
<button onClick={addThree}>+3 (adds only 1)</button>
</>
);
}Each call is setCount(0 + 1) on the first click. React queues three requests to set the value to 1, and the last one wins. The count goes from 0 to 1, not 3.
A table helps when you trace this kind of code. Here is the first click:
| Step | Code | Value of `count` in this handler | Queued request |
|---|---|---|---|
| 1 | `setCount(count + 1)` | 0 | set to 1 |
| 2 | `setCount(count + 1)` | 0 | set to 1 |
| 3 | `setCount(count + 1)` | 0 | set to 1 |
| After | React renders | 1 in the next render | none |
When the next value depends on the previous one
If a request depends on the latest pending state, pass an updater function instead of a value. React calls it during the next render with the pending state, so each queued updater sees the result of the one before it.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function addThree() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<>
<p>{count}</p>
<button onClick={addThree}>+3</button>
</>
);
}React processes the queue in order: 0 becomes 1, then 2, then 3. The chapter on updater functions covers this in detail. The point here is that snapshots are why you sometimes need one.
Mixing values and updaters
When a value request and an updater share a queue, React applies them in order. A value request replaces the pending state. An updater transforms it. Suppose count is 0 in the current render:
setCount(count + 5); // queue: replace with 5
setCount(c => c + 1); // queue: take previous (5), return 6
setCount(42); // queue: replace with 42The next render receives 42. The updater ran, but the final replacement overwrote its result. The first two requests were not lost. They were processed in order, and the last one set the final value.
Using the new value right away
Sometimes you need the new value inside the same handler, for example to send it to a server. Do not read the state variable after calling the setter. Compute the value once, in a local variable, and use it for both purposes.
import { useState } from 'react';
function Search() {
const [query, setQuery] = useState('');
function handleChange(e) {
const next = e.target.value;
setQuery(next);
console.log('searching for', next);
}
return <input value={query} onChange={handleChange} />;
}Here next is the value you intend to be state, and query is still the old snapshot.
Edge cases
- Objects and arrays. The snapshot is a reference to a value, not a deep copy. If you mutate an object in place, every closure holding that reference sees the change, and React may skip the render. Always create a new object or array. The chapter on immutability covers why.
- Props are snapshots too. A child's props are fixed for each render. A delayed callback in a child sees the props from the render in which it was created.
- Setting the same value. If you call a setter with a value equal to the current one (compared with
Object.is), React may skip re-rendering the component. Do not rely on this to prevent your own code from running. - Latest value needed later. If an asynchronous callback must read the latest value rather than the snapshot, an updater function or a
refcan do that. Choose deliberately, because it breaks the "what you see is what the handler uses" model.
Summary of the rules
- Each render has its own state values, props, and handlers.
- A setter schedules the next render. It does not change the current variable.
- Handlers and timeouts see the values from the render that created them.
- Several value requests in one handler use the same starting value, and the last one wins.
- Use updater functions when the next state depends on the pending state.
Exercise
A component has const [count, setCount] = useState(0);. On the first click the handler runs setCount(count + 1); setCount(count + 2); alert(count);. What does the alert show, and what does the component display after the click?
Show answer
The alert shows 0, because count is a snapshot from the render that created the handler. The queue holds "set to 1" followed by "set to 2", so the last request wins and the component displays 2 after re-rendering.
Exercise
In DelayedAlert, you type "Hi" and click the button. Within the three seconds you change the input to "Bye". What does the alert show, and why?
Show answer
It shows "Hi". The timeout callback was created during the render in which you clicked, and it closed over that render's message value. Later renders created new message constants but did not change the one the callback holds.