Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 132 ยท State and Events

How State Updates Work

Learn how React queues and batches state updates, why setCount(count + 1) three times adds only one, how functional updates fix stale values, StrictMode double calls and state versus refs.

In the last lesson you learned that state is a snapshot and that calling a setter asks React for a new render. That is enough to build a counter. It is not enough to understand why setCount(count + 1) called three times only adds one, why a timeout sometimes shows an outdated value, or why your updater function runs twice in development. Those puzzles all come from one mechanism: React queues your updates and processes them together, later, in a particular way.

This lesson opens that mechanism. You will see how batching works, how to write updates that depend on the previous state, what goes wrong when asynchronous code captures an old snapshot, what StrictMode does to updater functions, and when a ref is a better home for a value than state.

Updates are queued and batched

When a handler calls a setter, React does not re-render on the spot. It adds the update to a queue and, once the event handler has finished running, processes the whole queue and renders once. This is called batching. It keeps rendering efficient and guarantees that the screen never shows a half-updated mix of your state variables.

Three setters, one render

Click once. The console shows handler finished first, then a single render: Grace Hopper (1). There is never a render with "Grace Lovelace". Three setters, one render, and no intermediate state.

Batching applies to updates from every source in React 18 and later: event handlers, timeouts, promises and native event handlers. Older React versions batched only inside React event handlers, so code written for them sometimes expects extra renders that no longer happen.

Why setCount(count + 1) three times adds one

Now the famous puzzle. What do you expect this to do?

Calling the setter three times

The broken button adds 1, not 3. The reason is the snapshot: in this render, count is 0, so the handler contains three copies of setCount(0 + 1). React queues "replace the state with 1" three times and ends with 1. The fixed button adds 3, because it uses a different kind of update.

Functional updates

Instead of a value, you can pass the setter a function, called an updater function. React calls it with the most recent pending state and uses the return value as the next state.

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

The updater gets the state as processed so far in the queue, not the stale snapshot. Three of them in a row therefore chain: 0 -> 1 -> 2 -> 3.

Here is how React processes a queue. Suppose count is 0 when the handler runs:

Queued update Updater receives Result
setCount(count + 5) (value 5) 0 5
setCount((n) => n + 1) 5 6
setCount(42) 6 42

Direct values replace the state; updater functions transform what is there. After the handler, React renders with the final result, here 42. The name n in the updater is conventionally the first letter of the state variable (setAge(a => a + 1)) or prev/current.

Two rules for updaters: they must be pure (calculate the next state from the argument only, with no side effects, no mutation, no setState calls inside), and they must return the next state.

When do you need a functional update?

  • When the new state depends on the previous state and you may update more than once before a render (several calls in one handler, or calls from async code).
  • When you update state inside a setTimeout, setInterval or other delayed callback that may run after the state has moved on.
  • When you want to avoid listing the state as a dependency in an effect (see Effect Dependencies).

For a one-off setName(e.target.value) there is no previous state to depend on, so a plain value is perfect. Many teams simply use the updater form whenever the new value is derived from the old one, because it is correct by construction.

Updating after asynchronous work

Because handlers close over their render's snapshot, any code that runs later inside the handler sees the old values. Sometimes that is exactly what you want, and sometimes it is a bug. Look at a chat box that sends a message after a delay.

A delayed handler sees its own snapshot

Click Send, and within 150 ms switch the recipient to Grace. The log still says "Sent "Hello!" to Ada". The timeout captured message and recipient from the render in which you clicked, which is exactly what the user saw when they pressed the button, so the behavior is consistent and predictable. Note that clearing the input with setMessage('') does not affect the log either, for the same reason.

If you instead want "whatever is current when the timer fires", you cannot get it from the closure; you would read it from a ref (next section) or use an updater whose argument is the latest state:

JSX
setTimeout(() => {
  setLog((previous) => [...previous, 'latest log has ' + previous.length + ' entries']);
}, 150);

Notice also how the example appends to the log with setLog((previous) => [...previous, entry]). If two messages finish at nearly the same time, both updates are applied in order, whereas setLog([...log, entry]) would use the log from the snapshot and could lose an entry. Updating arrays and objects properly is the subject of Objects and Arrays in State.

Setting state with the same value

If the value you pass is identical to the current state according to Object.is, React bails out: it will not re-render the children or run their effects. (It may call your component function once more before deciding to bail out, which is harmless.) This is why mutating an object and passing the same reference never updates the screen.

Same value, no new render

After the first render, clicking "Set to 10 again" does not produce a new render, value = 10 line (React may log it once, as an optimisation check, but the output does not change). Clicking "Add one" renders 11.

StrictMode calls your updaters twice

React's StrictMode wrapper exists to help you find impure code. In development it renders components twice and also calls updater functions twice, then keeps one result. If your updater is pure, you cannot tell; if it mutates something or has side effects, the doubled call exposes the bug. StrictMode is off in our editor unless you add it yourself, so here we do.

StrictMode runs updaters twice

The console shows render, count = 0 twice at start (the component body runs twice). One click then logs updater call 1, current = 0 and updater call 2, current = 0, followed by render, count = 1 twice. The count still goes to 1: the second result is simply discarded. The counter variable is a deliberate impurity for the demo; never count calls inside a real updater. Production builds call everything once.

To make the point concrete, the next example does by hand what StrictMode does: it calls each updater twice with the same input and checks whether the two results agree.

Checking updaters for purity, StrictMode style

The impure updater returns a different answer each time because it changes extraItems as a side effect. With StrictMode switched on, that kind of bug shows up immediately as duplicated items or wrong totals instead of lurking until production. The same double-calling applies to component bodies and to initializer functions passed to useState. See Keeping Components Pure.

StrictMode never double-fires event handlers themselves. It double-invokes the things that must be pure (component bodies, updaters, initializers) and, for effects, runs an extra setup-and-cleanup cycle. The effect part is covered in Cleanup, Subscriptions and Timers.

Use state or a ref?

Not every value that changes belongs in state. A ref (useRef) is a box React keeps between renders just like state, but changing ref.current does not trigger a render and is visible immediately, with no snapshot semantics.

State Ref
Persists between renders Yes Yes
Changing it re-renders Yes No
Value read in render Safe, the snapshot Avoid (can be stale or inconsistent)
Updated immediately No, next render Yes
Use for Anything shown on screen Timer ids, previous values, DOM nodes, "latest value" for async code
State renders, refs do not

Click "Count in ref" three times: the console shows ref is now 3, but the screen still shows 0, because nothing rendered. Then click "Count in state": the render finally picks up the ref's current value and the screen shows both. Reading ref.current during render, as this demo does for illustration, is something to avoid in real components, because the displayed value only refreshes when something else triggers a render. Rule of thumb: if the user should see it, it is state; if it is bookkeeping, it can be a ref. More in useRef.

Putting it together: a checklist

When an update looks wrong, ask:

  1. Is the new value computed from the old one? Use the updater form.
  2. Am I reading state right after the setter and expecting the new value? You cannot; use a local variable for the new value.
  3. Is async or delayed code involved? It sees the snapshot of the render that created it.
  4. Am I mutating instead of replacing? React compares by reference.
  5. Does it work without StrictMode but not with it? Find the impurity.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With count = 0, a handler runs setCount(count + 1) three times. What is count after the next render?

    All three calls use the same snapshot value 0, so each queues "set to 1". The final state is 1. Use setCount(c => c + 1) to chain updates.
  2. 2. What does React do with several state updates triggered in one event handler?

    Updates are batched, so the component renders a single time with all queued changes applied. This applies to handlers, timeouts and promises alike.
  3. 3. State is 0. The handler calls setN(5); setN(n => n + 1); setN(42). What is the state afterwards?

    The queue is processed in order: 5, then 6 from the updater, then 42, because a plain value replaces the state.
  4. 4. Why does React call updater functions twice in StrictMode during development?

    Double-invoking pure functions is harmless, while impure ones show visible bugs. Only development builds do it.
  5. 5. Which value is best kept in a ref rather than in state?

    A timer id is bookkeeping that never appears in the UI, so changing it should not trigger a render. Everything displayed belongs in state.

Summary

  • React queues state updates and processes them after the handler finishes, rendering once (batching).
  • A setter called with a value replaces the state; called with a function, it transforms the latest pending state.
  • Use the functional form (setX(prev => ...)) when the new state depends on the old one, especially for repeated or delayed updates.
  • Async code and timeouts see the snapshot from the render that created them.
  • Setting an identical value (by Object.is) bails out without a visible re-render.
  • Updater functions and component bodies must be pure; StrictMode calls them twice in development to reveal impurity.
  • Use state for what appears on screen and refs for bookkeeping that should not cause a render.

Next: Objects and Arrays in State