Sub topic 14
Updater functions for updates based on previous state
This chapter assumes you know how useState works, can write event handlers in function components, and are comfortable with the spread operator and map/filter. It builds on the earlier chapters about state as a snapshot and replacing state with copies.
The problem: a snapshot does not change mid-handler
When a component renders, React hands it a snapshot of state. Every variable in that render, including todos, count, or person, holds the value from that snapshot. Calling a setter does not change those variables. It asks React to schedule a re-render with a new value.
That has a consequence when you call the same setter more than once in a single event handler. Look at this code:
import { useState } from 'react';
let nextId = 0;
export default function TodoList() {
const [todos, setTodos] = useState([]);
function addTwoBroken(title) {
setTodos([...todos, { id: nextId++, title, done: false }]);
setTodos([...todos, { id: nextId++, title: title + ' (copy)', done: false }]);
}
return (
<div>
<button onClick={() => addTwoBroken('Buy milk')}>Add two</button>
<ul>
{todos.map((t) => (
<li key={t.id}>{t.title}</li>
))}
</ul>
</div>
);
}You might expect two items after one click. You get one: "Buy milk (copy)". Both calls spread the same todos array from the current snapshot, which is empty. The first call queues "replace state with [Buy milk]". The second call queues "replace state with [Buy milk (copy)]". React applies the queue in order, and the last replacement wins.
What an updater function is
The setter accepts either a value or a function. When you pass a function, React calls it an updater function. It receives the latest pending state and returns the next state.
function addTwo(title) {
setTodos((prev) => [...prev, { id: nextId++, title, done: false }]);
setTodos((prev) => [...prev, { id: nextId++, title: title + ' (copy)', done: false }]);
}Now each call queues a function instead of a finished value. When React processes the queue during the next render, it feeds the result of each updater into the next one:
- Start with the current state,
[]. - Run the first updater with
[]. It returns[Buy milk]. - Run the second updater with
[Buy milk]. It returns[Buy milk, Buy milk (copy)]. - Use the final result as the state for the next render.
The handler still sees the old todos after both calls. Only the next render sees the new value.
A plain-number example
Counters show the effect most clearly, because there is no copying to distract you.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button
onClick={() => {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}}
>
Direct (+1)
</button>
<button
onClick={() => {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}}
>
Updater (+3)
</button>
</div>
);
}In the first button, count is 0 in all three calls, so you queue "set to 1" three times. The result is 1. In the second button, each updater receives the output of the previous one: 0 becomes 1, then 2, then 3.
How to write a good updater
The name of the parameter is yours to choose. Common conventions are the first letter of the state variable (c for count, t for todos), the full name prefixed with prev (prevCount), or old. Pick one and use it consistently.
An updater must follow the same rules as everything else in render logic:
- It must be pure. Given the same input it returns the same output, and it does nothing else.
- It must not mutate its argument.
prev.push(x); return prev;returns the same reference, so React sees no change. Copy first, as you did in earlier chapters. - It must not trigger side effects such as network calls, logging that matters, or calls to other setters.
In Strict Mode during development, React calls updater functions twice and ignores one of the results, to help you catch impure ones. This is also why the nextId++ inside the updater above is a weak pattern. In Strict Mode the counter can advance twice per item, which is harmless for unique keys but would be a real bug if the number meant something. Prefer computing an ID outside the updater, or use crypto.randomUUID() for a unique ID, and pass the finished item in.
function addTodo(title) {
const newTodo = { id: crypto.randomUUID(), title, done: false };
setTodos((prev) => [...prev, newTodo]);
}The new item is built once, outside the updater. The updater only adds it to the list, so running it twice gives the same answer.
Updater functions with objects and arrays
The patterns from earlier chapters carry over unchanged. You replace the value you would have spread from todos or person with the prev parameter.
// Object: update one field based on the previous object
setPerson((prev) => ({ ...prev, firstName: 'Grace' }));
// Nested object
setPerson((prev) => ({
...prev,
address: { ...prev.address, city: 'Paris' },
}));
// Array: remove
setTodos((prev) => prev.filter((t) => t.id !== id));
// Array: toggle one item
setTodos((prev) =>
prev.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
);Note the parentheses around the object in the first two lines. Without them, JavaScript reads { as the start of a function body, not an object literal, and the arrow function returns undefined.
When you need an updater and when you do not
You do not need an updater for every update. Passing a value is fine when the new state does not depend on state you may have already changed in the same batch. The table lists common situations.
| Situation | Direct value | Updater |
|---|---|---|
| Setting from an input's value (`setName(e.target.value)`) | Good | Not needed |
| Resetting to a fixed value (`setTodos([])`) | Good | Not needed |
| Several calls to one setter in one handler | Wrong result | Required |
| Update inside `setTimeout` or `await` that reads state | Reads stale value | Preferred |
| Update in an effect or callback with a memoized closure | May read stale value | Preferred |
| Single add or remove in an event handler | Works | Works |
The asynchronous case is easy to miss. A callback captures the snapshot from the render in which it was created.
import { useState } from 'react';
export default function DelayedCounter() {
const [count, setCount] = useState(0);
function handleClick() {
setTimeout(() => {
// count is the value from the render where this handler was created
setCount(count + 1);
}, 1000);
}
function handleClickSafe() {
setTimeout(() => {
setCount((c) => c + 1);
}, 1000);
}
return (
<div>
<p>{count}</p>
<button onClick={handleClick}>Add later (stale)</button>
<button onClick={handleClickSafe}>Add later (safe)</button>
</div>
);
}If you click the stale button three times within one second, all three timeouts close over count equal to 0 and the result is 1. With the updater, each timeout reads the latest queued state and the result is 3.
Many developers adopt a simple rule: when the next state is computed from the previous state, use an updater. It costs one extra arrow and removes a class of bugs.
Mixing an updater with a replacement
You can combine both forms in one handler. React processes the queue in order, and each entry either replaces the state or transforms it. Consider this handler:
function handleClick() {
setCount(count + 5);
setCount((c) => c + 1);
setCount(42);
}Starting from count equal to 0, React processes the queue like this:
| Queued update | `c` (input) | Result |
|---|---|---|
| `count + 5` (replacement) | 0 | 5 |
| `c => c + 1` | 5 | 6 |
| `42` (replacement) | 6 | 42 |
The final state is 42. A replacement discards whatever came before it, while an updater builds on it. Mixing the two in one handler is legal but hard to read, so avoid it unless you have a reason.
Common mistakes
- Calling the setter with the stale variable inside the updater. Writing
setTodos((prev) => [...todos, item])ignoresprevand brings the stale snapshot back. Use only the parameter inside the function. - Mutating
prev.setTodos((prev) => { prev.push(item); return prev; })returns the same array. React compares by reference, skips the re-render, and in Strict Mode the double call pushes the item twice. - Reading state right after setting it.
setCount(c => c + 1); console.log(count);logs the old value. If you need the next value, compute it in a variable first:const next = count + 1; setCount(next);. - Forgetting parentheses around an object literal.
prev => { ...prev, a: 1 }is a syntax error. Writeprev => ({ ...prev, a: 1 }). - Calling another setter inside an updater. Updaters must be pure, and with double invocation in Strict Mode the side effect runs twice. Do the extra work in the event handler.
Summary of the working model
React keeps a queue of pending updates for each piece of state. A direct value is queued as a replacement. An updater is queued as a function. At the next render React runs the queue from the start, passing the running result along, and renders once with the final value. The handler's own variables never change during that process.
Exercise
A component has const [score, setScore] = useState(10);. A button handler runs setScore(score + 2); setScore((s) => s * 3); setScore(score + 1);. What is the score after the next render, and why?
Show answer
The score is 11. The queue is processed in order starting from 10. setScore(score + 2) is a replacement with 12. (s) => s * 3 receives 12 and returns 36. setScore(score + 1) is a replacement with 11, because score is still 10 in this snapshot. The last replacement discards the earlier results, so the final state is 11.
Exercise
This handler is meant to add two items, but only one appears. Fix it, and explain why your fix works. function addPair(a, b) { setItems([...items, a]); setItems([...items, b]); }
Show answer
Use updater functions: setItems((prev) => [...prev, a]); setItems((prev) => [...prev, b]);. In the broken version both calls spread the same items snapshot, so the second replacement overwrites the first. With updaters, React passes the result of the first call to the second, so the final array contains both a and b. A single call such as setItems([...items, a, b]) would also work.
Exercise
Why is setTodos((prev) => { prev.push(item); return prev; }) a bug, even though it looks like it uses an updater?
Show answer
The updater mutates the previous array and returns the same reference. React compares the old and new state by reference, finds no difference, and may skip the re-render, so the screen does not update. In Strict Mode the updater is also called twice, which pushes the item twice. Return a new array instead: setTodos((prev) => [...prev, item]).