What is a state updater function?
A state updater function is a function you pass to a state setter, setCount((prev) => prev + 1), instead of a value. React calls it with the latest pending state and uses its return value as the next state. It guarantees correct results when several updates are queued or when the setter is called from a callback that may hold stale state.
Terminology
- The setter (or "set function") is what
useStatereturns:setCount. - The updater function is the callback you pass to it:
(prev) => prev + 1.
How React processes it
During the next render, React goes through the queue of updates for that state in order. Plain values replace the state; updater functions receive the result so far. Three setCount((c) => c + 1) calls produce +3; three setCount(count + 1) calls produce +1.
When to use it
- Next state depends on the previous state (counters, toggles, appending to arrays).
- Multiple updates in one event.
- Inside effects, intervals or subscriptions that would otherwise need the state as a dependency.
- Inside memoized callbacks (
useCallback) so they can have empty dependencies.
Rules
- Must be pure: no side effects, no mutation. In Strict Mode development React calls it twice to check.
- Return the new state (for objects, a new object).
- Naming convention: use the first letter of the state (
cfor count) orprev.
useReducer
A reducer is the generalization: every update goes through (state, action) => newState.
Code example
1import { useEffect, useState } from "react";23export function Score() {4 const [score, setScore] = useState(0);5 const [log, setLog] = useState<string[]>([]);67 function bonusRound() {8 // Updater functions: each receives the result of the previous one -> +309 setScore((s) => s + 10);10 setScore((s) => s + 10);11 setScore((s) => s + 10);12 setLog((l) => [...l, "bonus round"]);13 }1415 // No `score` dependency needed thanks to the updater16 useEffect(() => {17 const id = setInterval(() => setScore((s) => s + 1), 1000);18 return () => clearInterval(id);19 }, []);2021 return (22 <div>23 <p>Score: {score}</p>24 <button onClick={bonusRound}>Bonus</button>25 <ul>{log.map((l, i) => <li key={i}>{l}</li>)}</ul>26 </div>27 );28}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.