Part 03 / Topic 5 of 7
Updater functions: when the next value depends on the last
examples/04_functional_updates.jsx calls setCount three times in a row, meaning to add 3 to the count in one click:
// examples/04_functional_updates.jsx
export function TripleAddBroken() {
const [count, setCount] = useState(0);
function addThreeBroken() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
// ...
}
Clicking "Add 3" on TripleAddBroken really only moves the count by 1, not 3, per click (examples/04_functional_updates.test.jsx). count is a plain variable, captured once per render - the value this particular render started with, not a live link to "whatever the state is right now." All three calls above are really setCount(0 + 1), three separate times; React only needs to keep the last of several same-render updates that all compute from the same stale value. TripleAddFixed passes a function to setCount instead of a value:
// examples/04_functional_updates.jsx
export function TripleAddFixed() {
const [count, setCount] = useState(0);
function addThreeFixed() {
setCount((current) => current + 1);
setCount((current) => current + 1);
setCount((current) => current + 1);
}
// ...
}
React calls each updater function with the most up-to-date state it has queued so far - not the value this render started with - so the three calls really do build on each other. Clicking "Add 3" on TripleAddFixed really moves the count by 3 every time (examples/04_functional_updates.test.jsx): 3, then 6. The rule: reach for setX(valueExpression) when the next value does not depend on the current one (section 1's ClickCounter, section 4's CartFixed - both compute from other things, not purely from count's own last value in a batch), and reach for setX(current => ...) whenever more than one update to the same state might happen before React re-renders - which a single click handler calling the setter more than once always is.
Done here? The practice set for Part 3 — including the solutions — is on the part page.