State as a snapshot

Topic 3 of 4 in Interactivity & state7 min readIntermediateFree course

Overview

State behaves differently from a normal variable, and once you understand why, a whole category of confusing bugs disappears. The key idea: state is a snapshot. Each render sees its own fixed values, and setting state asks for a new render rather than changing the current one.

Setting state doesn’t change it now

JSX
function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
    console.log(count);   // still 0!
  }

  return <button onClick={handleClick}>{count}</button>;
}

setCount doesn’t reach in and change the count variable. count is a const holding the value React gave this render. The setter tells React: “next time you render this component, use 1”. Until that render happens, this handler keeps seeing 0.

It helps to picture each render as a photo: the JSX, the event handlers and every variable inside were all created with that render’s state values.

Three setters, one increment

JSX
function handleClick() {
  setCount(count + 1);
  setCount(count + 1);
  setCount(count + 1);
}

Clicking this once makes the counter show 1, not 3. Substitute the snapshot value and it’s obvious:

JSX
setCount(0 + 1);
setCount(0 + 1);
setCount(0 + 1);

All three say “set it to 1”.

Passing a value: setCount(count + 1) three times queues 0 + 1, 0 + 1, 0 + 1, so the next render has count 1. Passing an updater function: setCount(c => c + 1) three times queues 0 + 1, 1 + 1, 2 + 1, so the next render has count 3. Inside one render, count never changes.

Updater functions

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

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

Now each call says “take whatever the state is at that point, and add one”. React puts the functions in a queue and, during the next render, runs them in order: 0 → 1 → 2 → 3.

Convention: name the parameter after the first letter of the state (c for count, s for score) or prev.

When to use which

Pattern Use when
setCount(5) the new value doesn’t depend on the old one
setIsOpen(!isOpen) fine inside a simple click handler
setCount(c => c + 1) several updates in one handler, or updates from callbacks that might run later (timers, promises, subscriptions)

Using updaters everywhere for “increment”-style updates is a safe habit.

You can mix them, and React processes them in order:

JSX
setScore(10);            // replace with 10
setScore((s) => s * 2);  // then 20

Batching

React waits until all the code in an event handler has run before re-rendering — this is called batching. It’s like a waiter collecting the whole table’s order before going to the kitchen:

JSX
function handleReset() {
  setQuery('');
  setPage(1);
  setFilters([]);
  // one re-render after this function finishes, not three
}

Batching keeps apps fast and prevents half-updated screens where query has changed but page hasn’t. Since React 18, it applies everywhere: event handlers, timeouts, promises and native event listeners.

Snapshots and async code

Because state is a snapshot, async code sees the values from the render where it was created:

JSX
function SendButton() {
  const [message, setMessage] = useState('');

  function handleSend() {
    setTimeout(() => {
      alert(`You said: ${message}`);
    }, 3000);
  }

  return (
    <>
      <input value={message} onChange={(e) => setMessage(e.target.value)} />
      <button onClick={handleSend}>Send in 3s</button>
    </>
  );
}

Type “Hi”, click Send, then change the text to “Bye” within three seconds. The alert says “Hi”. That’s usually exactly what you want — the message that was there when you clicked. React’s snapshot behaviour protects you from race conditions where the data changes under your feet.

If you genuinely need the latest value inside a long-lived callback (an interval, a WebSocket listener), you’ll use updater functions, a ref (Refs and the DOM) or an Effect Event (Effect events).

A mental model

When you write:

JSX
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>+</button>

Think: “In this render, count is 3. This render’s button sets it to 4.” Every render has its own props, state, event handlers and JSX. Nothing from a past render changes; React just produces a new render with new values.

Debugging tip: if a value seems “stuck” or “one step behind”, look for code that reads state right after setting it, or callbacks created in an earlier render. The fix is usually to compute the next value into a variable, use an updater, or derive the value during render.

JSX
// Instead of reading state right after setting it…
const next = count + 1;
setCount(next);
sendAnalytics('count', next);   // use the value you computed
Exercise

Predict, then fix

This ScoreBoard should add 3 points when “+3” is clicked, and show an alert with the score from the moment of the click after 2 seconds. Predict what the buggy version shows, then fix the +3 button using updater functions. Explain (in a comment) why the delayed alert shows the old score even after the fix — and whether that is a bug.

JavaScript
import { useState } from 'react';

export function ScoreBoard() {
  const [score, setScore] = useState(0);

  function addThree() {
    setScore(score + 1);
    setScore(score + 1);
    setScore(score + 1);
  }

  function reportLater() {
    setTimeout(() => alert(`Score: ${score}`), 2000);
  }

  return (
    <div>
      <p>Score: {score}</p>
      <button onClick={addThree}>+3</button>
      <button onClick={reportLater}>Report in 2s</button>
    </div>
  );
}

Summary

  • Setting state doesn’t change the variable you already have — it requests a new render with the new value.
  • Within one render, a state variable is a fixed snapshot, even inside async callbacks and timeouts.
  • React batches all state updates in an event handler and re-renders once afterwards.
  • Pass an updater function — setCount(c => c + 1) — when the new state depends on the previous state.
  • Updater functions are queued and run in order during the next render.