Skip to content
jshacks.dev
Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Summarize in AI

Calling setCount(count + 1) three times in one handler adds one, not three, because every call reads the same count from that render. An updater function reads the latest queued value instead.

src/AddThree.jsxJSX
import { useState } from 'react';

export function AddThree() {
  const [direct, setDirect] = useState(0);
  const [updater, setUpdater] = useState(0);

  function handleClick() {
    setDirect(direct + 1);
    setDirect(direct + 1);
    setDirect(direct + 1);

    setUpdater((n) => n + 1);
    setUpdater((n) => n + 1);
    setUpdater((n) => n + 1);
  }

  return (
    <button onClick={handleClick}>
      direct {direct}, updater {updater}
    </button>
  );
}
Text
direct 0, updater 0     (before the click)
direct 1, updater 3     (after one click)

React batches the updates of one event and renders once. Each setDirect(direct + 1) was computed from the same direct of 0, so they all queue the value 1. Each n => n + 1 receives the result of the one before it, which gives 3. This queue is described in Updating state based on the previous state.

Use the updater form whenever the new value is derived from the old one, especially in timers and async code, where the closure may be stale.

Taggedreact 19
Share

More snippets

Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.