Skip to content
ClapelloNotes by Barath
ReactCh 05 · 3/6
Core3 min readUpdated

React / 24

State is a snapshot: batching & updater functions

TL;DR

Inside one render, state never changes. React batches your updates and applies them after the handler, so use setCount(c => c + 1) when the next value depends on the last.

Try it

Three updates, one click

Try it

count

0

  1. Click a button to see what the handler saw.
Both buttons call the setter three times and then console.log(count). Only the updater version adds 3, and both log the old value.

Every render has its own state

When React renders your component, it hands you that render's state values. Everything created during that render, including your event handlers, sees those values, and they never change inside that render.

// this render: count is 0
function handleClick() {
  setCount(count + 1); // setCount(0 + 1)
  setCount(count + 1); // setCount(0 + 1)
  setCount(count + 1); // setCount(0 + 1)
  console.log(count);  // 0
}

All three calls say "set it to 1". The next render gets 1.

Batching: one render, after the handler

React doesn't re-render after each setter call. It queues the updates and waits until your event handler has finished, then re-renders once. This is called batching, like a waiter who takes the whole table's order before going to the kitchen.

Batching means you never see a half-updated screen, and React doesn't waste renders. Since React 18 it happens everywhere: in event handlers, timeouts, promises and other callbacks.

The updater function

When the next value depends on the previous one, pass a function to the setter:

function handleClick() {
  setCount((c) => c + 1);
  setCount((c) => c + 1);
  setCount((c) => c + 1);
}

React puts the functions in the queue. On the next render it runs them in order, passing each one the result of the one before:

Queued updatec receivesReturns
c => c + 101
c => c + 112
c => c + 123

Values and functions can be mixed. setCount(count + 5) then setCount(c => c + 1) with count at 0 means "replace with 5", then "add 1": the result is 6.

Name the parameter after the state (c for count, prev or prevList for others). It's only a name.

Where it really matters: delayed code

Don't

Reads a stale snapshot

function handleClick() {
  setTimeout(() => setCount(count + 1), 1000);
}

Click three times within a second: all three timers were created in the render where count was 0, so the result is 1.

Do

Always gets the latest value

function handleClick() {
  setTimeout(() => setCount((c) => c + 1), 1000);
}

Three clicks, three increments: the result is 3.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.