Skip to content
Tutorials Center
My learning

Topics

React Reference ยท State Hooks

React useState updater functions

Reference for the functional form of setState in React: compute the next state from the previous one, queue several updates, and avoid stale values.

Besides a plain value, the setter returned by useState accepts a function. React calls that function with the pending state (the result of all updates queued before it) and uses the return value as the new state. This is called an updater function.

Use an updater whenever the next state depends on the previous one: counters, toggles, appending to a list. It always sees the latest queued value, even when many updates happen before the next render, and it keeps closures from capturing stale state.

JSX
setCount((previous) => previous + 1);

Try it

Three updates, one click

One click gives plain: 1 and updater: 3.

Mixing values and updaters

After one click n is 100: React walks the queue in order, feeding each result into the next updater.

Syntax

JSX
setState((previous) => next);
TypeScript
type Updater<S> = (previous: S) => S;
Name Description
previous The state as it will be after every update queued before this one. On the first update after a render it equals the rendered state.
return value The new state. Returning undefined stores undefined; it does not mean "no change".

Errors / edge cases: if the updater throws, the error surfaces during render and can be caught by an error boundary. An updater that returns the same value (by Object.is) bails out like a plain same-value update.

Usage notes

  • Updaters must be pure. They run during render, may run twice in StrictMode (development) and must not mutate previous, fetch data or call other setters. Return a new object or array instead.
  • Naming convention: use the first letter or the full name of the state (n => n + 1, todos => [...todos, todo]), or prefix with prev.
  • Not needed for every update. setName(e.target.value) does not depend on the old value, so a plain value is simpler. Reach for an updater when you read the same state you are writing.
  • Async code: callbacks that run later (timeouts, intervals, promise handlers) hold the state of the render that created them. An updater avoids the stale read: setTicks((t) => t + 1) inside setInterval keeps counting correctly with an empty dependency array.
  • Storing a function in state needs the updater form of a wrapper: setHandler(() => myFunction).
  • Not the same as flushSync. Updaters do not render sooner; they only make the queue arithmetic correct.
  • Objects: setUser((u) => ({ ...u, age: u.age + 1 })) merges one field safely even if another update to user is already queued.