Sub topic 6
Updating from the previous value with updater functions
This chapter assumes you can write function components, use useState with an event handler, and read arrow functions. You should also know that each render sees a fixed snapshot of state, covered in the previous chapter.
The problem: three updates, one increment
Calling a setter does not change the variable in your current handler. The count in that handler keeps the value it had when the component rendered. So this handler does not add three:
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>
</>
);
}When count is 0, addThreeWrong queues "set to 1" three times. Each call used the same snapshot value, so the result is 1.
What an updater function does
An updater function is a function you pass to the setter instead of a value. React calls it with the latest pending state and uses the return value as the next state.
In addThree, React queues three updaters and then processes them in order:
0goes in,1comes out.1goes in,2comes out.2goes in,3comes out.
Mixing values and updaters
React treats a plain value as an update that ignores earlier state. You can mix both kinds in one handler, and they run in the order you wrote them:
setCount(5); // queue: replace with 5
setCount(c => c + 1); // queue: take the result and add 1Starting from any value, the next state is 6.
When to use an updater
Use an updater whenever the next state depends on the previous state. Typical cases:
- Incrementing, decrementing, or toggling (
setOpen(o => !o)). - Several updates to the same state in one handler.
- Updates run later, such as inside a timeout, where your snapshot may be stale.
If the next state does not depend on the old one, such as setName(e.target.value), a plain value is correct and simpler.
Rules for updater functions
- Keep them pure. They should only compute the next state from the argument, with no side effects such as network calls. In development, React may call an updater twice to detect impure code.
- Do not mutate the argument. For objects and arrays, return a new one, for example
setTodos(list => [...list, newTodo]). - By convention, name the argument after the state, using its first letter (
cforcount) or a full name likeprevCount.
Exercise
A component has const [score, setScore] = useState(10);. A single click handler runs setScore(score + 5); setScore(s => s * 2); setScore(score + 1);. What is the score after the click?
Show answer
11. The first call queues "replace with 15", the second doubles that to 30, and the third queues "replace with 11" because score is still 10 in this snapshot. The last queued value wins, so the next state is 11.