React · Lesson 2

State

How React state really works, with useState and useReducer, state as a snapshot, functional updates, batching, immutable updates, derived versus duplicated state, lifting state up, and why hooks depend on their call order.

12 min read

In short

  • Setters ask for a new render; the variable doesn't change
  • Use setX((prev) => next) when it depends on the old value
  • Never mutate: new arrays and objects
  • Compute derived values, don't store copies
  • Call hooks at the top level, in the same order

Props come from the parent. State is the data a component remembers between renders: the text in a search box, which row is selected, whether a dialog is open. When state changes, React calls your component again and updates the screen to match.

Most React bugs are state bugs: a value that "doesn't update", a list that changes but the screen doesn't, two copies of the same data drifting apart, a counter that adds 1 when it should add 3. They all come from a wrong picture of what setState does. This lesson builds the right picture. The exercises then rebuild React's update queue, batching and hooks runtime, so none of it is magic.

useState

import { useState } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);          // [current value, setter]
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}
  • useState(initial) returns the current value and a setter. The initial value is only used on the first render. On later renders React gives you the stored value and ignores the argument.
  • If computing the initial value is expensive, pass a function: useState(() => parseDraft(localStorage)). React only calls it on the first render. useState(parseDraft(localStorage)) would parse on every render and throw the result away.
  • TypeScript infers the type from the initial value. When that's too narrow, say so: useState<User | null>(null), useState<string[]>([]). The TypeScript track's React & Angular patterns topic covers the typing in more depth.
  • The setter is stable: it's the same function on every render, so it never needs to be in a dependency array.

State is a snapshot

Calling the setter does not change the variable. It asks React for a new render, and only that next render sees the new value:

import { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
    console.log(count);   // still 0: this render's `count` is a constant
  }
  // After the click, count is 1, not 3: all three calls asked for 0 + 1.

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

Each render is a function call with its own count, and every event handler created during that render sees that render's value forever. That's why a setTimeout or setInterval callback can show an old value: it was created by an old render (a stale closure).

Functional updates

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

import { useState } from 'react';

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

  function handleClick() {
    setCount((c) => c + 1);
    setCount((c) => c + 1);
    setCount((c) => c + 1);   // count becomes 3
  }

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

React keeps a queue of updates for each piece of state. On the next render it starts from the current value and applies the queue in order: a value replaces the state, a function receives the result so far. So [count + 1, count + 1, count + 1] with count = 0 ends at 1, and three c => c + 1 updaters end at 3.

Use the function form whenever the update depends on the previous state and might run in a batch or from an old closure: counters, toggles (setOpen((o) => !o)), appending to lists, intervals. Updater functions must be pure, because in development Strict Mode calls them twice to catch side effects. One more consequence: since any function passed to a setter is treated as an updater, storing a function in state needs a wrapper, setOnConfirm(() => deleteInvoice). Exercise 1 builds this queue.

Batching and bail-outs

React doesn't re-render after each setter call. Since React 18 it batches every update made in the same tick, whether in an event handler, a setTimeout, or after an await, and renders once:

import { useState } from 'react';

export function SaveButton({ save }: { save: () => Promise<void> }) {
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [savedAt, setSavedAt] = useState<Date | null>(null);

  async function handleClick() {
    setSaving(true);
    setError(null);              // these two: one render
    try {
      await save();
      setSaving(false);
      setSavedAt(new Date());    // these two: one render
    } catch (e) {
      setSaving(false);
      setError(String(e));
    }
  }

  return <button disabled={saving} onClick={handleClick}>{saving ? 'Saving…' : 'Save'}</button>;
}
  • If an update produces a value that is Object.is-equal to the current one, React bails out: it skips re-rendering the children (it may still call this component once to be sure).
  • To force a synchronous render (rarely needed, for example to measure the DOM right after an update), wrap the update in flushSync from react-dom.
  • Batching makes separate setters cheap, but three flags that always change together (saving, error, savedAt) are still often clearer as one state object or a reducer, which can't drift into an impossible combination. Exercise 4 builds a batching scheduler.

Immutable updates

The bail-out compares references with Object.is. If you mutate state and pass the same object back, React sees the same reference and does nothing:

▶ Try
type Todo = { id: number; title: string; done: boolean };
const todos: Todo[] = [{ id: 1, title: 'Write tests', done: false }];

const mutated = todos;
mutated.push({ id: 2, title: 'Ship', done: false });
console.log('after push, same reference?', Object.is(todos, mutated));   // true: React would skip the render

const copied = [...todos, { id: 3, title: 'Celebrate', done: false }];
console.log('after spread, same reference?', Object.is(todos, copied)); // false: React re-renders

So treat state as read-only and create new objects and arrays:

Instead ofWrite
arr.push(x)[...arr, x]
arr.splice(i, 1)arr.filter((t) => t.id !== id)
arr[i] = xarr.map((t) => (t.id === id ? x : t)) or arr.with(i, x)
arr.sort(), arr.reverse()arr.toSorted(), arr.toReversed() (ES2023), or copy first
obj.name = 'Ann'{ ...obj, name: 'Ann' }
obj.address.city = 'Oslo'{ ...obj, address: { ...obj.address, city: 'Oslo' } }
  • Copy only the path that changes. Unchanged items keep their references, which is what lets memo components skip work.
  • useState doesn't merge objects (unlike old class components' this.setState). setUser({ name }) replaces the whole user. Spread the old one in: setUser((u) => ({ ...u, name })).
  • For deep updates, Immer lets you write mutating code on a draft and produces the immutable result: setInvoice(produce((draft) => { draft.lines[2].qty = 3; })). Redux Toolkit uses it inside every reducer.
  • Mark state types readonly (readonly Todo[], Readonly<Todo>) and TypeScript rejects push and assignments at compile time. Exercise 2 practises this.

useReducer

When several pieces of state change together, or the next state depends on what happened rather than on a new value, move the logic into a reducer: a pure function (state, action) => newState.

import { useReducer } from 'react';

type State = { items: readonly Item[]; query: string; page: number };
type Action =
  | { type: 'searched'; query: string }
  | { type: 'pageChanged'; page: number }
  | { type: 'loaded'; items: readonly Item[] };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'searched':    return { ...state, query: action.query, page: 1 };   // a new search resets the page
    case 'pageChanged': return action.page === state.page ? state : { ...state, page: action.page };
    case 'loaded':      return { ...state, items: action.items };
  }
}

export function SearchPage() {
  const [state, dispatch] = useReducer(reducer, { items: [], query: '', page: 1 });
  return <SearchBox value={state.query} onChange={(query) => dispatch({ type: 'searched', query })} />;
}
  • Actions describe what happened ('searched'), and the reducer decides what that means for the state. The rule "a new search resets the page" lives in one place, instead of in every event handler.
  • The reducer must be pure: no API calls, no Date.now(), no mutation. React may call it more than once (Strict Mode does), and you can unit test it with plain function calls.
  • Returning the same state object for a no-op action lets React bail out.
  • dispatch is stable, like a setter. Passing dispatch down (or through context) is a common way to let deep children trigger updates.
  • The TypeScript track's React & Angular patterns topic covers typing reducers, including exhaustive switch with never. Exercises 3 and 6 build a cart reducer and a reusable undo/redo reducer.

Derived state: compute, don't copy

If a value can be computed from props or other state, compute it during render. Don't store it:

import { useMemo, useState } from 'react';

export function TodoPage({ todos }: { todos: readonly Todo[] }) {
  const [filter, setFilter] = useState<'all' | 'open' | 'done'>('all');
  const [selectedId, setSelectedId] = useState<number | null>(null);

  // ✓ derived: always in sync, nothing to update
  const visible = todos.filter((t) => filter === 'all' || (filter === 'done') === t.done);
  const selected = todos.find((t) => t.id === selectedId) ?? null;
  const openCount = useMemo(() => todos.filter((t) => !t.done).length, [todos]); // memo only if it's expensive

  // ✗ duplicated: const [visible, setVisible] = useState(todos) plus an effect to keep it in sync
  // ✗ duplicated: const [selected, setSelected] = useState<Todo | null>(null), a copy that goes stale when todos change
  return null;
}
  • Every copy is a second source of truth that someone has to keep in sync, usually with an effect that renders twice and still shows a wrong frame in between.
  • Store the id of the selected item, not a copy of the item.
  • useMemo is a performance tool for expensive computations, not a way to "store" derived values. In a project that uses the React Compiler, you rarely write it by hand: the compiler memoizes computations like these for you (see the Performance topic).
  • useState(props.value) copies a prop once. Later changes to the prop are ignored. If you need the prop, use the prop. If you need an editable copy that resets when the prop's identity changes, use a key (see Components & props).

Lifting state up

When two components need the same state, move it to their closest common parent and pass it down with a callback to change it:

import { useState } from 'react';

export function FaqList({ items }: { items: readonly Faq[] }) {
  const [openId, setOpenId] = useState<string | null>(null);   // one source of truth
  return items.map((faq) => (
    <Panel
      key={faq.id}
      title={faq.question}
      isOpen={openId === faq.id}
      onToggle={() => setOpenId((id) => (id === faq.id ? null : faq.id))}
    >
      {faq.answer}
    </Panel>
  ));
}

Each Panel used to own an isOpen state, so several could be open at once. Lifting the state to FaqList makes "only one open" a simple rule. The panels become controlled (Components & props topic). Lift only as high as needed: state at the top of the app re-renders the whole app when it changes. When passing props through many layers gets painful, the Context topic has the next tools.

Hooks are identified by call order

useState doesn't take a name. So how does React know which state is which? It keeps a list of hook slots for each component instance and hands them out by position: the first useState call gets slot 0, the second gets slot 1, and so on. That's the whole reason for the Rules of Hooks: call them at the top level, in the same order, on every render, and never inside conditions, loops or after an early return.

▶ Try
// A tiny version of React's hook storage: one array per component, read by call order.
const slots: unknown[] = [];
let cursor = 0;

function useState<S>(initial: S): S {
  const index = cursor++;
  if (!(index in slots)) slots[index] = initial;
  return slots[index] as S;
}

function render(component: () => string): string {
  cursor = 0;
  return component();
}

let showAge = true;
function Profile(): string {
  const name = useState('Ann');
  if (showAge) useState(31);         // ✗ a conditional hook
  const city = useState('Oslo');
  return `${name} lives in ${city}`;
}

console.log(render(Profile));
showAge = false;
console.log(render(Profile));          // city now reads the slot that held the age

React detects some of these mistakes ("Rendered fewer hooks than expected", "Rendered more hooks than during the previous render"), but a swap like the one above can silently show wrong data. The eslint-plugin-react-hooks rules catch them before they run. The one exception is React 19's use(), which reads a promise or a context and, unlike hooks, may be called inside conditions and loops. Exercise 5 builds this runtime with setters, re-renders and those errors.

Common mistakes

  • Reading state right after setting it and expecting the new value.
  • setCount(count + 1) in a timer, an interval or a batch, where setCount((c) => c + 1) was needed.
  • Mutating state (push, sort, obj.x = ...) and wondering why nothing re-renders, or why it re-renders with surprising data later.
  • Expecting useState to merge objects like class components did.
  • Copying props or other state into state, then syncing it with an effect.
  • Five useStates that always change together. Use one object or a reducer.
  • Calling hooks conditionally, or after an early return.

In a real codebase

Side note
  • Local state (useState) for UI details: open, hovered, the draft text of an input.
  • Lifted state in a parent for what siblings share.
  • Server data (lists, details, anything from an API) usually lives in a cache library such as TanStack Query, not in useState plus an effect. It handles loading, caching, refetching and races for you.
  • URL state (filters, page, selected tab) in the router's search params, so a page can be shared and reloaded.
  • Global client state (the signed-in user, feature flags, a shopping cart) in context, Zustand or Redux Toolkit. The Context topic covers when each one fits.
  • If you know Angular signals: useState is signal(), the setter with a function is .update(), and derived values are computed(). The big difference is granularity: a signal update only marks the components whose templates read it for checking, while a React state update re-runs the whole component function (and, by default, its children) and diffs the output.

The exercises

  1. The update queue: how React applies values and updater functions, and why count + 1 three times adds 1.
  2. Immutable todo updates: add, toggle, rename and remove without mutating, keeping unchanged items' references.
  3. Cart reducer: a reducer with an action union, bail-outs for no-op actions, and derived totals.
  4. Batched updates: a scheduler that batches setter calls into one render, with snapshots, bail-outs and flushSync.
  5. A hooks runtime: useState and useReducer stored by call order, with re-renders and React's hook-order errors.
  6. Undo and redo: a generic higher-order reducer with history, limits, ignored actions and grouped edits.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.

Open in the app