Sub topic 6
Updating from the previous value with updater functions
This chapter assumes you can declare state with useState, call a setter from an event handler, and explain that each render sees a fixed snapshot of state. It also assumes you know arrow functions and spread syntax. Here you will learn how to pass a function to a setter so the next state is computed from the latest pending state instead of from the snapshot.
The problem: the snapshot goes stale
Inside one render, count is a constant. Calling setCount(count + 1) three times in a row queues three updates that all say "set the state to 1".
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function addThreeWrong() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
function addThree() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<>
<p>{count}</p>
<button onClick={addThreeWrong}>+3 (adds only 1)</button>
<button onClick={addThree}>+3</button>
</>
);
}The first button adds 1 per click because every call reads the same count. The second button adds 3 because each call receives the result of the one before it.
What an updater function is
An updater function is a function you pass to the setter instead of a value. React calls it later with the latest pending state and uses its return value as the next state.
setCount(prev => prev + 1);By convention, the parameter is named after the state variable's first letter (c) or with a prev prefix (prevCount). The name does not matter to React. A clear name helps when several state variables are in play.
How React processes the queue
When a handler runs, React does not change state immediately. It adds each call to a queue for that state variable. On the next render, React walks the queue in order, starting from the previous state.
- A plain value replaces the pending state.
- An updater function receives the pending state and returns the new pending state.
Suppose number starts at 0 and a handler runs these three lines.
setNumber(number + 5);
setNumber(n => n + 1);
setNumber(42);| Queued update | Pending state before | Pending state after |
|---|---|---|
| `setNumber(number + 5)` | 0 | 5 |
| `setNumber(n => n + 1)` | 5 | 6 |
| `setNumber(42)` | 6 | 42 |
The final state is 42. A later plain value overrides everything before it. An updater queued after a value builds on that value.
When the snapshot is stale in async code
A handler's closure keeps the count from the render that created it. Delayed code can therefore overwrite newer changes.
import { useState } from 'react';
function DelayedCounter() {
const [count, setCount] = useState(0);
function addLater() {
setTimeout(() => {
setCount(c => c + 1);
}, 1000);
}
return <button onClick={addLater}>Added: {count}</button>;
}Click three times within one second. With setCount(count + 1), each timeout closes over count from the render where you clicked, which is 0. The final value is 1. With the updater form, each timeout reads the latest pending state and the final value is 3.
The same applies to promise callbacks and to any handler that runs after an await.
Updaters with objects and arrays
Updaters return new objects and arrays. Spread, map, and filter work the same way as before, but they operate on the updater's parameter instead of the snapshot.
import { useState } from 'react';
function Scoreboard() {
const [player, setPlayer] = useState({ name: 'Ada', score: 0 });
function addTwo() {
setPlayer(p => ({ ...p, score: p.score + 1 }));
setPlayer(p => ({ ...p, score: p.score + 1 }));
}
return (
<button onClick={addTwo}>
{player.name}: {player.score}
</button>
);
}The parentheses around { ... } matter. Without them, the braces are parsed as a function body and the updater returns undefined.
Rules for updater functions
React expects an updater to be pure. A pure function returns the same output for the same input and changes nothing outside itself.
- Compute the new state from the argument only.
- Do not mutate the argument. Return a new object or array.
- Do not call other setters, write to
localStorage, fetch data, or log from inside it. - Always return a value. A forgotten
returnsets the state toundefined.
In development, Strict Mode calls each updater twice and ignores one result. If your updater has a side effect, you will see it happen twice. That is a signal that the code is impure.
import { useState } from 'react';
function Tags() {
const [tags, setTags] = useState([]);
// Wrong: mutates the previous array, so the double call adds the tag twice.
function addWrong(tag) {
setTags(prev => {
prev.push(tag);
return prev;
});
}
// Right: returns a new array and leaves prev untouched.
function add(tag) {
setTags(prev => [...prev, tag]);
}
return (
<>
<button onClick={() => add('react')}>Add</button>
<p>{tags.join(', ')}</p>
</>
);
}The wrong version also returns the same array reference, so React may skip the re-render.
Choosing between a value and an updater
Both forms are correct in many cases. Use this table to decide.
| Situation | Use |
|---|---|
| New state does not depend on old state, such as `setOpen(false)` | Value |
| New state is computed from old state, such as a counter or toggle | Updater |
| Several updates to the same state in one handler | Updater |
| Update runs in a timeout, interval, or after an `await` | Updater |
| New state comes from an input event, such as `e.target.value` | Value |
Many teams use updaters whenever the new value depends on the old one. The cost is a few characters, and it removes a whole class of stale-value bugs.
A related benefit is that an updater lets a callback avoid reading state at all. A function that only calls setCount(c => c + 1) does not need count from the surrounding scope, so it stays correct even if it is captured by an older render.
Common errors
- Mixing forms and expecting addition.
setCount(count + 1)followed bysetCount(c => c + 1)does not add 2 from the snapshot in the way you might expect. The value form replaces the pending state withcount + 1, and the updater then adds 1 to that result. This works here, but reversing the order loses the updater's change. - Passing the result of a call.
setCount(increment())runsincrementduring render of the handler and passes its return value. To pass an updater, pass the function itself, as insetCount(increment). - Reading state right after the call. After
setCount(c => c + 1), the variablecountin the same handler is still the old snapshot. The updater does not change that. - Side effects in the updater. Move them into the event handler, after the setter call, or into an effect.
When updaters get crowded
If a handler chains many updaters across several state variables, the logic is spread out and hard to follow. That is the point where moving the transitions into a reducer starts to pay off. A later chapter covers useReducer.
Exercise
A component has const [count, setCount] = useState(0). A handler runs setCount(count + 1); setCount(c => c + 1); setCount(count + 10); in a single click. Starting from 0, what is the count after the next render, and why?
Show answer
The count is 10. React processes the queue in order. The first call sets the pending state to 1. The updater turns it into 2. The last call is a plain value, count + 10 with the snapshot count equal to 0, so it replaces the pending state with 10.
Exercise
This handler is meant to add one item to the end of an array state, but in Strict Mode the item appears twice: setItems(prev => { prev.push(item); return prev; }). Why does it happen, and how do you fix it?
Show answer
React calls updater functions twice in development to expose impurities. The updater mutates prev, so the push happens twice on the same array. Return a new array instead: setItems(prev => [...prev, item]).