Skip to content

State as a Snapshot

The Course
•
20 min study

The last lesson ended with a surprise: right after setMinutes, minutes still had its old value. This lesson explains why, because it causes real bugs.

Predict

Counter's Add 3 button calls setCount(count + 1) three times. Before you click, write down what the heading will show after one click.

Add 3? React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import Counter from "./Counter.jsx"; export default function App() { return ( <main> <h1>Two counters</h1> <Counter label="Pages read" /> <Counter label="Exercises done" /> </main> ); } import { useState } from "react"; export default function Counter({ label }) { const [count, setCount] = useState(0); function addThree() { setCount(count + 1); setCount(count + 1); setCount(count + 1); console.log(label, "count during this click:", count); } return ( <section className="card"> <h2>{label}: {count}</h2> <button onClick={addThree}>Add 3</button> </section> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Check your prediction

The count goes up by 1, not 3. The console says count during this click: 0.

Each render has its own values

When React calls Counter, count is fixed for that whole render. During the first click, count is 0 everywhere in that function, so the three calls are really:

JavaScript
setCount(0 + 1);
setCount(0 + 1);
setCount(0 + 1);

Each one says "make it 1". React applies them in order, ends up at 1, and then re-renders. In the next render, count is 1.

Think of each render as a snapshot: its props, its state and its event handlers all see the values from that moment.

The updater function

When the next value depends on the previous one, pass setCount a function instead of a value:

JavaScript
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);

React queues the three functions, then runs them one after another. Each gets the result of the one before it: 0 → 1 → 2 → 3. Make that change in Counter.jsx and click Add 3 again.

You don't need an updater function every time. setCount(count + 1) is fine for a single update. Reach for c => c + 1 when you update the same state more than once in one event, or when the update happens later, such as in a timer.

Each component has its own state

App uses Counter twice. Click one, then the other. Each keeps its own count. State belongs to one place on the screen: two Counters means two separate counts, even though they share the same code:

JSX
export default function App() {
  return (
    <main>
      <h1>Two counters</h1>
      <Counter label="Pages read" />
      <Counter label="Exercises done" />
    </main>
  );
}

Your turn

Exercise

Which updates need an updater?

Add two buttons to Counter, and decide for each one whether it should call setCount with a value or with an updater function:

  • Reset sets the count back to 0.
  • Add 1 later adds 1 after two seconds. Use the browser's timer to wait: setTimeout(() => { ...code to run later... }, 2000);

Then click Add 1 later three times quickly and wait. The heading should end at 3, not 1. Before you run it, write down why.

Your working space React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import Counter from "./Counter.jsx"; export default function App() { return ( <main> <h1>Two counters</h1> <Counter label="Pages read" /> <Counter label="Exercises done" /> </main> ); } import { useState } from "react"; export default function Counter({ label }) { const [count, setCount] = useState(0); function addThree() { setCount(count + 1); setCount(count + 1); setCount(count + 1); console.log(label, "count during this click:", count); } return ( <section className="card"> <h2>{label}: {count}</h2> <button onClick={addThree}>Add 3</button> </section> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Ask two questions of each update. Does the new value depend on the old one? And by the time the update runs, could the old value it read be out of date? A timer's function is made during one render but runs later, after other clicks may have happened.

Hint 2: a first step

Write Add 1 later with setCount(count + 1) inside the timer first. Click it three times quickly: two seconds later the heading shows 1. All three timers were made while count was 0, so each one asks for 0 + 1. That's the bug; now change what you pass to setCount inside the timer. Does Reset have the same problem?

Show one solution
JavaScript
function reset() {
  setCount(0);
}

function addOneLater() {
  setTimeout(() => {
    setCount((c) => c + 1);
  }, 2000);
}
JSX
<button onClick={reset}>Reset</button>{" "}
<button onClick={addOneLater}>Add 1 later</button>

Reset doesn't need an updater: 0 doesn't depend on the old count, so a stale snapshot can't make it wrong. Add 1 later does. The three timers all come from renders where count was 0, so setCount(count + 1) would ask for 1 three times. The updater asks React for the latest value when it runs, so the three timers give 1, 2, 3.

Was this article helpful?

Your response is saved on this device.