The useState Hook

The useState Hook in React: --- A factory stockroom keeps one painted number on a big count board: the current quantity of a part.


The Analogy: A Stockroom Count Board and the Clerk's Slip Box

A factory stockroom keeps one painted number on a big count board: the current quantity of a part. Every worker on the floor can read that board at a glance, all shift long. What no worker may do is grab a brush and repaint it. The board is not scratch paper; it is the single agreed truth for the shift, and it stays fixed while the shift runs.

To change the count you fill out a change-slip and drop it in the clerk's box: "SET TO 12" or "ADD 1 TO CURRENT." You do not touch the board yourself. Between shifts the clerk empties the box, applies the slips in order, repaints the board with the result, and only then does the next shift begin -- now reading the new number. Filing a slip does not change what you see this shift; it changes what everyone sees next shift.

This gap explains a subtlety that trips everyone. Suppose the board reads 0 and, during your shift, you drop three slips that each say "SET TO (the number I see) + 1." You saw 0 on all three, so all three say "SET TO 1," and the clerk repaints 1 -- not 3. But if your three slips instead say "ADD 1 TO WHATEVER IT IS," the clerk applies them one after another and the board ends at 3. A slip that names an absolute value freezes the number you read; a slip that describes an adjustment composes with the others.

The discipline collapses the moment someone repaints the board by hand. A worker who scribbles a new number directly onto the board bypasses the clerk entirely; the next repaint overwrites the scribble, other shifts saw a value that never officially existed, and nobody can reconstruct how the count got there. Every stockroom keeps its own board, too -- one room's worker cannot read or repaint another's. The count is private, and it only ever changes through a slip.


Syntax or Core Structure

useState gives a function component a private count board. You call it with the initial value; it returns a pair: the current value and a setter (the slip box). Calling the setter files a change and schedules a re-render -- it does not repaint the variable in place.

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      You clicked {count} times
    </button>
  );
}

A live click and re-render cannot be printed, so model a render as a pure function of the current value, and simulate the clerk repainting the board between renders. Each console.log stands for one render's view.

function view(count) {
  return "You clicked " + count + " times";
}

let count = 0;
console.log(view(count));   // first render, board reads 0
count = count + 1;          // a "+1" slip is applied before the next render
console.log(view(count));   // re-render, board reads 1
count = count + 1;
console.log(view(count));   // re-render, board reads 2

Output:

You clicked 0 times
You clicked 1 times
You clicked 2 times

The view is a pure function of count; the only thing that moves between lines is the value the clerk repainted. That is the whole model of state: render from the current value, file a slip to change it, render again.


Technical Depth: Snapshots, Updaters, and Closures

Absolute slip versus adjustment slip

Inside one event handler, count is frozen at the value from that render -- the number you read off the board. If you file several "set to snapshot + 1" slips, they all name the same result; if you file "adjustment" slips (functional updaters), each sees the latest queued value.

Call, with count = 0, run 3x in one handlerReadsFinal
setCount(count + 1)the render snapshot, 01
setCount(c => c + 1)the latest queued value3
// snapshot slips: all three computed from the same render value, 0
const snapshot = 0;
let s = snapshot;
s = snapshot + 1;
s = snapshot + 1;
s = snapshot + 1;
console.log("snapshot updates ->", s);

// adjustment slips: each updater sees the latest value
const upd = (c) => c + 1;
let f = 0;
f = upd(f);
f = upd(f);
f = upd(f);
console.log("functional updates ->", f);

Output:

snapshot updates -> 1
functional updates -> 3

A handler sees the render that created it

An event handler is created during a render and closes over that render's value. Even if state later moves on, the handler still reads the number it captured.

function makeReader(count) {
  return () => count;
}

const readAtZero = makeReader(0);   // captured when the board read 0
console.log("closure sees:", readAtZero());

Output:

closure sees: 0

Lazy initial value runs once

Passing a function to useState makes React call it only on the first render. Passing the already-computed value re-runs the work every render instead.

let builds = 0;
function build() { builds++; return 42; }

const initial = build();   // stand-in for useState(build) -- called once
console.log("value:", initial, "builds:", builds);

Output:

value: 42 builds: 1

Updating arrays and objects without mutating

State is replaced, never edited, so array and object updates build a fresh copy and hand that to the setter. The originals stay untouched -- which is exactly what lets React compare old and new.

const cart = ["pen", "ink", "nib"];
const added = [...cart, "pad"];
const removed = cart.filter((x) => x !== "ink");
const renamed = cart.map((x) => (x === "nib" ? "point" : x));

console.log("added:   ", added.join(","));
console.log("removed: ", removed.join(","));
console.log("renamed: ", renamed.join(","));
console.log("original:", cart.join(","));

Output:

added:    pen,ink,nib,pad
removed:  pen,nib
renamed:  pen,ink,point
original: pen,ink,nib

Objects follow the same rule: spread the old one, then override the field you mean to change, so the rest survives.

const user = { name: "Ada", age: 30 };
const older = { ...user, age: 31 };

console.log("old:", user.name, user.age);
console.log("new:", older.name, older.age);

Output:

old: Ada 30
new: Ada 31

Derive values, do not store them

If a value can be computed from state you already hold, compute it during render. Storing it as a second piece of state is a standing invitation for the two to disagree.

const items = [{ price: 3 }, { price: 5 }, { price: 2 }];
const total = items.reduce((sum, it) => sum + it.price, 0);

console.log("count:", items.length, "total:", total);

Output:

count: 3 total: 10

A sequence of slips, traced

Real state moves through many transitions. Modeling each as a pure function from old list to new list keeps every step immutable and easy to trace -- add, toggle, and remove never touch the previous array.

const add = (list, text) => [...list, { text, done: false }];
const toggle = (list, i) =>
  list.map((t, j) => (j === i ? { ...t, done: !t.done } : t));
const remove = (list, i) => list.filter((_, j) => j !== i);
const show = (list) =>
  list.map((t) => (t.done ? "[x] " : "[ ] ") + t.text).join(" | ") || "(empty)";

let s = [];
s = add(s, "write");
s = add(s, "test");
s = add(s, "ship");
console.log("after adds:  ", show(s));
s = toggle(s, 1);
console.log("after toggle:", show(s));
s = remove(s, 0);
console.log("after remove:", show(s));

Output:

after adds:   [ ] write | [ ] test | [ ] ship
after toggle: [ ] write | [x] test | [ ] ship
after remove: [x] test | [ ] ship

Each transition returns a new list and the setter would receive it whole -- setTodos(list => add(list, text)) in real code. Because none of add, toggle, or remove mutates its input, you could log every intermediate list and they would all still hold their original contents; that auditability is the practical payoff of immutable updates, and it is exactly the shape useReducer formalizes when these transitions grow numerous.

Independent boards stay independent

Unrelated values belong in separate useState calls. Repainting one board never disturbs another, so an update to the counter leaves the name exactly where it was.

let name = "Ada";
let count = 0;
count = count + 1;   // only the count board is repainted
console.log("name:", name, "count:", count);

Output:

name: Ada count: 1

The variable does not move mid-handler

Filing a slip does not repaint the board during the current shift, so reading the state variable immediately after calling its setter still returns the old snapshot. This is the single most common source of "my log prints the wrong number" confusion.

function handler(count, log) {
  log.push("before:            " + count);
  // setCount(count + 1) is filed here, but count is still the snapshot
  log.push("after filing slip: " + count);
}

const log = [];
handler(0, log);
console.log(log.join("\n"));

Output:

before:            0
after filing slip: 0

Real World Example: A "+2" Button That Only Adds One

A common feature: a button that should bump a counter by two in a single click. The obvious handler calls the setter twice. Modeled deterministically, here is what each style actually produces from a starting value of 0.

// Handler that files two "set to snapshot + 1" slips.
// FLAW: both calls read the same render snapshot of count.
function plusTwoByValue(countSnapshot) {
  let next = countSnapshot;
  next = countSnapshot + 1;   // setCount(count + 1)
  next = countSnapshot + 1;   // setCount(count + 1) again -- same snapshot
  return next;                // React keeps the last write: snapshot + 1
}

// Handler that files two adjustment slips.
function plusTwoByUpdater(countSnapshot) {
  const queue = [(c) => c + 1, (c) => c + 1];
  return queue.reduce((c, fn) => fn(c), countSnapshot);
}

console.log("start:", 0);
console.log("+2 by value   ->", plusTwoByValue(0));
console.log("+2 by updater ->", plusTwoByUpdater(0));

Output:

start: 0
+2 by value   -> 1
+2 by updater -> 2

The button looks correct in the source -- it plainly calls the increment twice -- which is exactly why the bug is so common. The rendered counter goes up by one per click, quietly, and a quick manual test that clicks slowly never reveals anything wrong. The intent (+2) and the behavior (+1) diverge only because of how state is read.

The honest half is plusTwoByUpdater. Each updater is an adjustment slip: reduce feeds the first updater the start value 0, gets 1, feeds that to the second, and gets 2. Because every step consumes the latest value rather than a frozen reading, stacking updates composes exactly as intended, no matter how many are queued in one handler.

The flaw lives in plusTwoByValue. Both count + 1 expressions close over the same render snapshot of count (here, 0), so both compute 1; React applies "set to 1" and then "set to 1" again, and the board lands on 1. The two writes did not stack -- the second overwrote the first with an identical value. The fix is the functional updater setCount(c => c + 1), which reads the latest queued value each time. The same trap has a sibling for object state: setUser({ age: 31 }) replaces the whole object and silently drops name, because state is replaced, never merged.


Common Mistakes

  1. Repainting the board by hand. Mutating state directly -- count++, arr.push(x), obj.key = v -- bypasses the setter, so React never schedules a re-render and the change is lost or inconsistent.
  1. Expecting the value to change synchronously. Right after setCount(5), the count variable is still the old snapshot; the new value appears only on the next render.
  1. Stacking snapshot updates. Calling setCount(count + 1) several times in one handler lands on one increment; use setCount(c => c + 1) when the next value depends on the previous.
  1. Calling Hooks conditionally. A Hook inside an if, a loop, or a nested function changes the call order between renders and corrupts which state belongs to which Hook.
  1. Replacing an object and dropping fields. setUser({ name }) throws away every other key because state is replaced, not merged; spread first: setUser(u => ({ ...u, name })).
  1. Computing the initial value eagerly. useState(buildBig()) runs buildBig on every render; only useState(() => buildBig()) defers it to the first render.
  1. Storing derived data in state. Keeping a "total" in state next to the items it sums invites drift; derive it during render instead.
  1. Initializing state from props and expecting it to follow. The initial argument is read only on the first render; later prop changes do not flow into that state.
  1. One mega-object for unrelated values. Bundling every field into a single state object forces careful spreading on every update; split independent concerns into separate useState calls.

Best Practices

  • Treat state as immutable. Always hand the setter a brand-new value, object, or array; never edit the existing one in place.
  • Use the functional updater for dependent updates. When the next value is built from the current one, setX(prev => ...) is correct regardless of batching.
  • Keep the minimum state. Store only what cannot be computed, and derive everything else during render to avoid drift.
  • Split unrelated values. Independent concerns each get their own useState, so an update to one never has to spread the others.
  • Initialize costly values lazily. Pass a function to useState when the initial value is expensive to build.
  • Name the pair consistently. [thing, setThing] makes the setter's target obvious at every call site.
  • Keep Hooks at the top level. Call them unconditionally and in a stable order, never inside branches or loops.
  • Reach for useReducer when updates get tangled. Several coupled setters that always move together are usually one reducer in disguise.

Practice Exercises

  1. Predict the final value when a handler calls setCount(count + 1) three times with count starting at 0, then rewrite it with the functional updater so it truly adds three; confirm both with the queue-reduce model.
  1. Declare const [on, setOn] = useState(false) and a handler setOn(v => !v); hand-trace the value after three toggles and state which render each value belongs to.
  1. Given const [user, setUser] = useState({ name: "Ada", age: 30 }), write the setter call that raises only age to 31 without losing name, and explain exactly what setUser({ age: 31 }) would leave behind.
  1. Convert useState(buildBigList()) to lazy initialization and, using a call counter like the builds example, state how many times the builder runs across three renders in each form.