Sub topic 14
Updater functions for updates based on previous state
This chapter assumes you know useState, event handlers, the spread operator, and map and filter. You have already seen how to replace state with a new copy. Here you will learn what to do when the new value depends on the old one and you set state more than once in the same event.
The problem: state is a snapshot
Inside one render, a state variable holds a fixed value. Calling a setter does not change that variable. It asks React to render again with a new value. If you call a setter twice and both calls read the same variable, both calls start from the same old value.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function addThreeWrong() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
return <button onClick={addThreeWrong}>Count: {count}</button>;
}In the first click, count is 0 in all three calls. Each call queues "set to 1", so the result is 1, not 3.
The fix: pass an updater function
An updater function is a function you pass to the setter instead of a value. React puts it in a queue. During the next render, React runs the queued updaters in order. Each one receives the result of the previous one as its argument. By convention, you name that argument after the state, such as prev or the first letters of the state name.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function addThree() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return <button onClick={addThree}>Count: {count}</button>;
}The three updaters run as 0 → 1 → 2 → 3, so one click adds three.
Updater functions with arrays and objects
The same rule applies to arrays. The updater must return a new array and must not change prev.
function addTwo(title) {
setTodos((prev) => [...prev, { id: nextId++, title, done: false }]);
setTodos((prev) => [
...prev,
{ id: nextId++, title: title + ' (copy)', done: false },
]);
}With plain setTodos([...todos, newItem]) twice, the second call would overwrite the first, because both spread the same todos. With updaters, both items are added.
For objects, return a spread copy:
setPerson((prev) => ({ ...prev, firstName: 'Grace' }));The parentheses around the object literal matter. Without them, JavaScript reads the braces as a function body and returns undefined.
When you need an updater
| Situation | Direct value | Updater |
|---|---|---|
| New value does not depend on the old one, such as `setName('Ada')` | Fine | Not needed |
| One update per event, using the current render's value | Usually fine | Fine |
| Several updates to the same state in one event | Loses updates | Required |
| Updating state inside a delayed callback, such as `setTimeout` | May use a stale value | Safer |
Updaters are never wrong, so many teams use them whenever the next value is computed from the previous one.
Common errors
- Mutating
prev. WritingsetTodos((prev) => { prev.push(x); return prev; })returns the same array, so React sees no change. - Forgetting to return. A function body in braces needs an explicit
return. - Side effects inside the updater. React may call updaters more than once in development to check that they are pure. Keep them free of side effects. Using
nextId++inside an updater, as in the example above, increments a variable outside the function. The extra call makes ids skip numbers. Compute ids before calling the setter, or generate them in the event handler. - Mixing styles. After
setCount(5), a followingsetCount((c) => c + 1)gives6. React treats a plain value as an updater that ignores its argument.
Exercise
A button handler runs setCount(count + 5); setCount((c) => c + 1); setCount(count + 2); where count is 10 in the current render. What is the count after the next render, and why?
Show answer
12. The first call queues "set to 15". The updater then turns 15 into 16. The last call queues "set to 12", which ignores the previous result and replaces it. The final queued value is 12.