The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·25

State Management

Classify state before choosing tools: local, server, URL, form, session, global, persistent and derived state. Then Context, reducers, Redux, Zustand, signals, observables and state machines, plus the server-state concerns of caching, staleness, invalidation, optimistic updates, pagination, retries and cancellation.

31 topics · ~28 min read · 27-question quiz
Updated Suggest a correction

Start here: where data lives in a frontend

"State" is several different things

State is any data that can change while the app runs and affects what's shown. Beginners treat it as one thing and put it all in one place; experienced engineers first ask what kind of state it is, because each kind has a natural home:

Kind Examples Natural home
UI state is this dropdown open? which tab is selected? the component that shows it (useState, a signal)
Form state what's typed so far, validation errors the form (a form library or local state)
Shared client state the cart, the theme, the logged-in user a store or context near the top of the app
Server state the menu, orders, user profile: data whose source of truth is the server a server-state cache (TanStack Query, framework loaders)
URL state the current page, search query, filters, sort order the URL (so it survives reload and can be shared)
Persistent state saved preferences, drafts localStorage/IndexedDB, or the server

The single most useful question is: who owns the truth? If the server owns it (the menu), the frontend only holds a copy that can go stale, which needs caching, refetching and invalidation, not a global variable. If the user is editing it right now (a form field), the component owns it.

Keep state as local as possible

Start with state inside the component that uses it. Move it up ("lift" it, chapter 21) only when another component needs it, to their nearest common parent. When many distant components need the same data (the cart badge in the header and the checkout page), passing props through every layer in between (prop drilling) gets tedious; that's when a shared store or context earns its place.

And never store what you can compute. A cart total derived from the cart lines should be calculated (and memoised if expensive), not kept in its own variable that someone will forget to update.

Reducers: changes as named events

As shared state grows, scattered setX(...) calls make it hard to know what changed and why. A reducer centralises it: every change is an action (a plain object naming what happened), and one pure function computes the next state from the current state and the action:

JavaScript
function cart(state, action) {
  switch (action.type) {
    case "added": {
      const existing = state.lines.find(l => l.id === action.dish.id);
      const lines = existing
        ? state.lines.map(l => (l.id === action.dish.id ? { ...l, qty: l.qty + 1 } : l))
        : [...state.lines, { ...action.dish, qty: 1 }];
      return { ...state, lines };
    }
    case "removed": return { ...state, lines: state.lines.filter(l => l.id !== action.id) };
    case "couponApplied": return { ...state, coupon: action.code };
    default: return state;
  }
}
const total = s => s.lines.reduce((sum, l) => sum + l.price * l.qty, 0) * (s.coupon === "CHAI10" ? 0.9 : 1);   // derived, never stored

Feeding it five actions:

Text
 0 (start)        lines: -                     | total ₹0
 1 added          lines: Masala dosa×1         | total ₹90
 2 added          lines: Masala dosa×1, Idli×1 | total ₹140
 3 added          lines: Masala dosa×2, Idli×1 | total ₹230
 4 couponApplied  lines: Masala dosa×2, Idli×1 | total ₹207
 5 removed        lines: Masala dosa×2         | total ₹162
replaying the log gives the same state: true
the original states are untouched (time travel works): 1 2

Because the reducer is pure (no network calls, no Date.now(), no mutation), every state is reproducible from the list of actions: you can test it without a browser, log actions to debug ("what happened before the bug?"), undo by going back one state, and replay a user's session. React's useReducer, Redux, NgRx and Elm all use this pattern.

Server state is a cache, not a variable

The most common state-management mistake is copying server data into a global store by hand: fetch the menu in an effect, dispatch({ type: "menuLoaded" }), and then write code for loading flags, errors, refetching, deduplication, staleness and invalidation, again and again for every endpoint. Server data has different problems from client data:

  • It can be stale: someone else changed it.
  • Several components may ask for it at the same time.
  • Requests can fail, be slow, arrive out of order (chapter 15).
  • After you change it (a mutation), cached copies must be invalidated.

Server-state libraries (TanStack Query, SWR, RTK Query, Apollo for GraphQL, and framework loaders) solve this once. You describe what you need by a key, and the library handles fetching, caching and freshness:

JSX
function useMenu() {
  return useQuery({ queryKey: ["menu"], queryFn: () => fetch("/api/menu").then(r => r.json()) });
}
function MenuCount() { const { data } = useMenu(); return <p>{data?.length ?? "…"} dishes</p>; }

Three components called useMenu() on the same page; the lab counted one request, and when the menu was hidden and shown again it rendered instantly from the cache, with no request at all.

Making impossible states impossible

A loading UI written with independent booleans (isSubmitting, isError, isDone) has 2³ = 8 combinations, but only four make sense. One forgotten reset, and the screen shows a spinner, an error and a success message together. Measured with a sequence of events (submit, fail, retry, succeed, submit, succeed):

Text
event      boolean flags                    | explicit state machine
submit   → isSubmitting                    | submit   → submitting
failure  → isError                         | failure  → error
retry    → isSubmitting + isError          | retry    → submitting
success  → isError + isDone                | success  → done
submit   → isSubmitting + isError + isDone | submit   → submitting
success  → isError + isDone                | success  → done

The flags drifted into states that can't exist ("error and done"). A single status value with explicit allowed transitions (a state machine) can only ever be in one valid state, and an event that doesn't make sense in the current state ("submit" while already submitting: a double-click) is simply ignored. In TypeScript, a discriminated union (chapter 16) gives the same guarantee: { status: "error"; message: string } | { status: "done"; orderId: string } | ….

How deep to go in state management

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Classify state and name the tools for each kind
L2 Keep state local, lift it correctly, use a reducer, a store and a server-state library
L3 Explain re-render propagation through context vs selectors, cache keys and staleness, optimistic updates and rollback, state machines
L4 Diagnose over-rendering, stale or duplicated data, lost updates, race conditions and inconsistent UI states
L5 Design an app's state architecture: what lives where, cache policies, URL design, offline and sync strategy
L6 Run it at scale: real-time sync, local-first engines, conflict resolution, observability of client state

Classify first

The kinds of state

"Which state management library should we use?" is the wrong first question. Most state-management pain comes from treating different kinds of state the same way, for example putting server data into a global Redux store and hand-writing cache logic. Classify each piece of state first. Each kind has a natural home:

Kind Examples Owner / home Lifetime
Local UI state Is this dropdown open? Hover, current tab in a widget, input draft The component (useState, a signal) While mounted
Server state Orders, products, the user profile: data whose source of truth is the backend A server-state cache (TanStack Query, SWR, RTK Query, Apollo), framework loaders, or RSC Cached, stale, refetched
URL state Search query, filters, sort, page, selected item, active tab of a page The URL (router, URLSearchParams) Shareable, bookmarkable, survives reload
Form state Field values, touched/dirty, validation errors, submission status A form library (React Hook Form, TanStack Form, Angular reactive forms) or native forms + FormData Until submitted or reset
Session / auth state Current user, roles, tokens, CSRF token An auth provider (context or service); HttpOnly cookies on the server side (chapter 28) Session
Global client state Theme, sidebar collapsed, a client-only shopping cart, feature flags, a toast queue, a multi-step wizard spanning routes A small global store (Context, Zustand, signals, NgRx SignalStore) App lifetime
Persistent state Preferences, drafts, an offline queue localStorage, IndexedDB (chapter 17), synced to the server where it matters Across sessions
Derived state Totals, filtered lists, validation summaries, "is the form submittable?" Computed from other state, never stored separately —

After moving server data to a query cache and filters to the URL, most apps find that the "global state" left over is small: a theme, a session, maybe a cart. That changes the library question from "which big framework?" to "which small tool?"

Where state should live

Within the component tree, put state as low as possible but as high as necessary: in the lowest common ancestor of every component that reads or writes it. State that's too high re-renders too much and couples unrelated components. State that's too low gets duplicated and drifts. When many distant components need it, use context or a store instead of drilling props through intermediate layers.

Client state tools

Context

React Context (chapter 22) and Angular's DI services (chapter 23) are the built-in ways to share values across a subtree. Context is dependency injection, not a store:

  • It's good for low-frequency values: theme, locale, the current user, a service object, configuration.
  • It's poor for high-frequency values: every consumer re-renders when the value changes, and you can't subscribe to part of a context value.
  • Pattern: put a stable object (a store instance, or dispatch functions) into context, and let consumers subscribe to fine-grained slices through selectors. That's what Zustand-with-context, Jotai and Redux's Provider do.

Reducers

A reducer is a pure function (state, action) => newState (chapter 22's useReducer). Its advantages carry over to any scale:

  • All transitions in one place: easy to read, review and test (call the function, assert the result).
  • Events, not setters: dispatch { type: "itemAdded", item } (what happened) rather than setItems(...) (how to change it), which keeps business intent visible and supports logging and undo.
  • Time travel and replay: since state is a fold over actions, recording the actions reproduces the state. This is event sourcing (Vol. 5) on the client.

Redux and Redux Toolkit

Redux (2015) is one global store, holding a tree of state, updated only by dispatching actions through reducers, with middleware for side effects and selectors for reading. Plain Redux needed a lot of boilerplate. Redux Toolkit (RTK) is the official, modern way to write it:

TypeScript
import { createSlice, configureStore, type PayloadAction } from "@reduxjs/toolkit";

const cartSlice = createSlice({
  name: "cart",
  initialState: { items: [] as CartItem[] },
  reducers: {
    itemAdded(state, action: PayloadAction<CartItem>) {
      const existing = state.items.find(i => i.id === action.payload.id);
      if (existing) existing.qty += 1;           // "mutating" syntax is safe: Immer produces an immutable update
      else state.items.push({ ...action.payload, qty: 1 });
    },
    itemRemoved(state, action: PayloadAction<string>) {
      state.items = state.items.filter(i => i.id !== action.payload);
    },
  },
});

export const store = configureStore({ reducer: { cart: cartSlice.reducer } });
export const { itemAdded, itemRemoved } = cartSlice.actions;
type RootState = ReturnType<typeof store.getState>;
export const selectCartCount = (s: RootState) => s.cart.items.reduce((n, i) => n + i.qty, 0);

// Component: subscribe to exactly what you need; re-renders only when that value changes
const count = useSelector(selectCartCount);
const dispatch = useDispatch();
dispatch(itemAdded(product));

Strengths: predictability, Redux DevTools (action log, state diffs, time travel), a mature ecosystem, RTK Query for server state, and a pattern that scales to large teams. Weaknesses: ceremony for small apps, a single global store that encourages over-globalising, and the temptation to put server data in it. Use it for large apps with complex, cross-cutting client state and many contributors, and use RTK Query (or TanStack Query) for server data. Angular's equivalent is NgRx Store (actions, reducers, effects, selectors) or the lighter NgRx SignalStore.

Zustand

Zustand is a minimal store: a hook created from a function, with no providers, no actions or reducers required, and selector-based subscriptions:

TypeScript
import { create } from "zustand";
import { persist } from "zustand/middleware";

type CartState = {
  items: CartItem[];
  add: (p: Product) => void;
  remove: (id: string) => void;
  clear: () => void;
};

export const useCart = create<CartState>()(
  persist(                                       // middleware: persist to localStorage
    (set) => ({
      items: [],
      add: (p) => set((s) => ({
        items: s.items.some(i => i.id === p.id)
          ? s.items.map(i => (i.id === p.id ? { ...i, qty: i.qty + 1 } : i))
          : [...s.items, { ...p, qty: 1 }],
      })),
      remove: (id) => set((s) => ({ items: s.items.filter(i => i.id !== id) })),
      clear: () => set({ items: [] }),
    }),
    { name: "cart" },
  ),
);

const count = useCart((s) => s.items.length);    // re-renders only when this selected value changes
const add = useCart((s) => s.add);

It's tiny, needs little boilerplate, works outside React too (useCart.getState()), and is a good default for modest global client state. Jotai (atomic state, bottom-up) and Valtio (proxy-based mutable state) come from the same authors, with different models.

Signals

Signals (chapter 23) are reactive values with automatic dependency tracking: reading a signal inside a computation or render subscribes to it, and writing it notifies exactly those dependents. They're fine-grained: no whole-component re-render and diff, just the affected bindings updated.

TypeScript
// Framework-agnostic illustration (Preact Signals API; Solid, Angular, Vue and Svelte runes are similar)
import { signal, computed, effect } from "@preact/signals-core";

const items = signal<CartItem[]>([]);
const count = computed(() => items.value.reduce((n, i) => n + i.qty, 0));   // derived, memoised, glitch-free
effect(() => { document.title = `Cart (${count.value})`; });              // re-runs when count changes

items.value = [...items.value, { id: "p1", qty: 1, price: 200 }];         // title updates automatically
Framework Signals
Solid createSignal, createMemo. Components run once, and only bindings update
Angular signal, computed, effect, linkedSignal, resources (chapter 23)
Vue ref, computed, watch (Proxy-based)
Svelte 5 $state, $derived, $effect runes (compiled)
Preact @preact/signals
Qwik useSignal (resumable)
React Not built in. React's model is re-render + diff, with the React Compiler handling memoisation. Libraries (Jotai, Preact signals for React, MobX) add signal-like behaviour
JavaScript itself TC39 Signals proposal (stage 1): a standard primitive frameworks could share

Signals versus re-render-and-diff (React): signals give more precise updates with less wasted work, and they're excellent for high-frequency updates. React's model keeps components as plain functions of state, which is simpler to reason about, and the compiler closes much of the performance gap.

Observable models

Observable-based state (RxJS BehaviorSubject services in Angular, MobX observables in React, Elf, and older Knockout) models state as streams or observable objects that views subscribe to. MobX makes classes reactive: mark fields observable and methods action, and components wrapped in observer re-render when the fields they read change. It's essentially signals with an object-oriented API. RxJS-based stores (BehaviorSubject + scan) are natural in Angular codebases built around streams. The trade-off is that implicit reactivity is magical: it's powerful, but harder to trace than explicit actions.

State machines

Many UI bugs are impossible state combinations: isLoading && isError, a submit button clickable while submitting, a modal that's "closing" and "open" at once. Booleans multiply: five booleans allow 32 combinations, of which maybe six are valid. A finite state machine (Vol. 1 ch. 5 relations and graphs; chapter 16's discriminated unions) makes the valid states and the allowed transitions explicit:

editing validating processing succeeded failed SUBMIT VALID INVALID SUCCESS FAILURE RETRY
A checkout payment flow as a state machine. Events are only accepted in states that define them, so a double "submit" while processing is simply ignored.
TypeScript
// XState v5 (statecharts: hierarchical/parallel states, guards, actions, invoked async actors)
import { setup, fromPromise, assign } from "xstate";

export const paymentMachine = setup({
  actors: { charge: fromPromise(({ input }: { input: { amount: number } }) => api.charge(input.amount)) },
  guards: { isValid: ({ context }) => context.amount > 0 },
}).createMachine({
  id: "payment",
  initial: "editing",
  context: { amount: 0, error: null as string | null },
  states: {
    editing:   { on: { SUBMIT: [{ guard: "isValid", target: "processing" }, { target: "editing" }] } },
    processing: {
      invoke: {
        src: "charge", input: ({ context }) => ({ amount: context.amount }),
        onDone: "succeeded",
        onError: { target: "failed", actions: assign({ error: ({ event }) => String(event.error) }) },
      },
      // SUBMIT isn't handled here → double-clicks are ignored by construction
    },
    succeeded: { type: "final" },
    failed:    { on: { RETRY: "processing", EDIT: "editing" } },
  },
});

Use state machines for complex flows: checkout and payment, wizards, media players, drag-and-drop, connection lifecycles (WebSocket reconnecting), authentication flows, and anything with timeouts and retries. For simple components, a discriminated-union useReducer gives most of the benefit. Statecharts (David Harel, 1987) add hierarchy and parallelism. XState can visualise machines and generate test paths from them.

Server state

Server state is fundamentally different from client state. It's remote (the backend owns it), asynchronous, shared (other users change it), and can go stale. Managing it means solving caching, deduplication, background refresh, invalidation, pagination, retries and cancellation. That's a database-replication problem in miniature (Vol. 5), and it's why dedicated libraries exist:

Library Ecosystem
TanStack Query React, Vue, Solid, Svelte, Angular
SWR React (Vercel)
RTK Query Redux
Apollo Client / urql / Relay GraphQL (normalised caches)
Angular httpResource / resource + signals Angular
Framework loaders, RSC + fetch caching Next.js, React Router, SvelteKit, Nuxt (chapter 24)

The cache

TanStack Query stores results in a cache keyed by a query key, an array that identifies the data and its parameters:

TSX
import { useQuery, useMutation, useQueryClient, keepPreviousData } from "@tanstack/react-query";

function useOrders(filters: { status?: string; page: number }) {
  return useQuery({
    queryKey: ["orders", filters],                                   // cache key: deterministic, includes every parameter
    queryFn: ({ signal }) => api.getOrders(filters, { signal }),     // receives an AbortSignal
    staleTime: 30_000,                                               // fresh for 30 s: no refetch on mount or focus
    placeholderData: keepPreviousData,                               // keep showing the last page while the next loads
  });
}

function Orders() {
  const [params, setParams] = useSearchParams();                     // filters live in the URL (URL state)
  const filters = { status: params.get("status") ?? undefined, page: Number(params.get("page") ?? 1) };
  const { data, isPending, isError, error, isFetching, refetch } = useOrders(filters);
  if (isPending) return <OrdersSkeleton />;
  if (isError) return <ErrorPanel error={error} onRetry={refetch} />;
  return <OrdersTable orders={data.items} refreshing={isFetching} />;
}

What the cache gives you for free:

  • Deduplication: ten components using ["orders", filters] cause one request.
  • Shared data: every consumer of a key sees the same result and re-renders when it updates.
  • Instant navigation back: cached data shows immediately, then refreshes in the background.
  • Garbage collection: unused entries are removed after gcTime (5 minutes by default).
  • SSR integration: prefetch on the server, dehydrate, and hydrate the client cache.

Stale data and staleness

Two separate timers govern cached data:

  • staleTime: how long data is considered fresh. Fresh data is served without refetching. The default is 0, meaning always stale, so it's refetched on every mount, window focus and reconnect. Raise it for data that doesn't change often (a product catalogue at 5 minutes, user settings at Infinity until mutated).
  • gcTime (formerly cacheTime): how long unused data stays in memory.

Stale-while-revalidate behaviour: when a stale key is used, the library returns the cached (stale) data immediately and refetches in the background, then updates. Triggers include mount, window refocus (refetchOnWindowFocus), network reconnect, intervals (refetchInterval for polling), and manual invalidation. This is chapter 19's HTTP caching model, implemented in application memory.

Invalidation

After a mutation, cached data that depended on it is wrong. Invalidation marks it stale and refetches whatever is on screen:

TSX
function useCancelOrder() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => api.cancelOrder(id),
    onSuccess: (_data, id) => {
      qc.invalidateQueries({ queryKey: ["orders"] });            // prefix match: every orders list (any filters)
      qc.invalidateQueries({ queryKey: ["order", id] });         // the detail view
    },
  });
}

Design query keys hierarchically (["orders"], ["orders", filters], ["order", id], ["order", id, "items"]) so invalidation can target a whole family by prefix. Alternatives and complements:

  • Write the response into the cache (setQueryData) when the mutation returns the updated entity, which avoids a refetch.
  • Server-driven invalidation: push "order 42 changed" through WebSocket or SSE (chapter 19) and invalidate that key. That's how you keep multiple users' views fresh.
  • Normalised caches (Apollo, Relay, RTK Query tags) update an entity once and every query containing it reflects the change automatically. They're more powerful and more complex.

Phil Karlton's line "There are only two hard things in computer science: cache invalidation and naming things" applies here as much as anywhere.

Optimistic updates

An optimistic update applies the expected result to the UI immediately, before the server confirms it, then rolls back if the server rejects it. The UI feels instant, which suits likes, toggles, reordering, adding to cart and chat messages:

TSX
const toggleDone = useMutation({
  mutationFn: (todo: Todo) => api.updateTodo(todo.id, { done: !todo.done }),
  onMutate: async (todo) => {
    await qc.cancelQueries({ queryKey: ["todos"] });                 // stop in-flight refetches overwriting our change
    const previous = qc.getQueryData<Todo[]>(["todos"]);              // snapshot for rollback
    qc.setQueryData<Todo[]>(["todos"], (old = []) =>
      old.map(t => (t.id === todo.id ? { ...t, done: !t.done } : t)));
    return { previous };
  },
  onError: (_err, _todo, ctx) => {
    qc.setQueryData(["todos"], ctx?.previous);                       // roll back
    toast.error("Couldn't update. Your change was undone.");
  },
  onSettled: () => qc.invalidateQueries({ queryKey: ["todos"] }),   // re-sync with the server's truth either way
});

React 19's useOptimistic (chapter 22) does the same for actions. Guidelines: be optimistic only when failure is rare and easily reversible. Be careful with payments, irreversible actions, and anything where a rollback would confuse the user. Make mutations idempotent (idempotency keys) so retries don't double-apply. Show subtle pending indicators.

Pagination and infinite scrolling

There are two pagination models, and the backend decides which one you can use (Vol. 3):

Offset pagination (?page=3&size=20) Cursor / keyset pagination (?after=o_1042&limit=20)
Jump to page N ✓ ✗ (sequential)
Stable under inserts and deletes ✗ (items shift between pages, causing duplicates and skips) ✓
Performance on deep pages Poor (OFFSET 100000 scans and discards rows) Constant (index seek, Vol. 4)
UI fit Numbered pages, admin tables Infinite scroll, feeds, "load more"
TSX
const feed = useInfiniteQuery({
  queryKey: ["feed"],
  queryFn: ({ pageParam, signal }) => api.getFeed({ after: pageParam, limit: 20 }, { signal }),
  initialPageParam: undefined as string | undefined,
  getNextPageParam: (last) => last.nextCursor ?? undefined,          // undefined → no more pages
});
// feed.data.pages.flatMap(p => p.items); feed.fetchNextPage() when an IntersectionObserver sentinel appears (ch. 17)

For infinite lists: virtualise long lists (chapter 27), restore scroll position on back navigation (cached pages help), give keyboard and screen-reader users a "Load more" button as well as auto-loading (chapter 20), and announce new items with a live region.

Retries

Server-state libraries retry failed queries automatically. TanStack Query retries 3 times by default, with exponential backoff, in the browser. Apply chapter 15's rules:

  • Retry queries (reads are idempotent). Don't retry mutations by default, unless they're idempotent (with an idempotency key).
  • Don't retry 4xx responses (except 408 and 429). Retrying a 404 or 403 just delays the error. Configure retry: (count, err) => err.status >= 500 && count < 3.
  • Respect Retry-After on 429 and 503.
  • Pause retries while offline. The library resumes on reconnect (networkMode).
  • Surface errors after the retries are exhausted, with a manual retry button.

Cancellation

When a query's result is no longer needed (the component unmounted, the key changed because the user typed again, or a newer request superseded it), the request should be cancelled to save bandwidth and server work and to prevent stale overwrites (chapter 15's race conditions). TanStack Query passes an AbortSignal to queryFn. Forward it to fetch (or axios), and the library aborts automatically. RxJS's switchMap (chapter 23) and React Router's loaders (request.signal) do the same. For mutations, cancellation is rarely safe: the server may already have applied the change. That's another reason to use idempotency keys and to treat "no response" as unknown (Vol. 1 ch. 9).

Local-first and sync engines

A growing architecture inverts the model. The client holds a local database (IndexedDB or SQLite-Wasm on OPFS) as the primary state, and a sync engine replicates changes to and from the server in the background, often using CRDTs (conflict-free replicated data types, Vol. 5) or server-authoritative rebasing. Reads and writes are instant and work offline, and multi-user collaboration comes built in. Examples include Linear's sync engine, Figma's multiplayer, Replicache/Zero, ElectricSQL, PowerSync, Automerge and Yjs (collaborative editing), and InstantDB. It's powerful for collaborative and offline apps, and it brings distributed-systems problems (conflicts, schema migrations on clients, authorisation of synced data) into the frontend.

Lab: state tools, measured

React 19 with Zustand 5.0 and TanStack Query 5, bundled with esbuild and run in Chromium 153 against a small Node API; the reducer and state-machine experiments in Start here ran in Node 22.

Experiment 1: one big context versus a store with selectors

Three memo-wrapped components read different parts of the same app state: a cart badge (the cart), a user name, and a theme toggle. Version A puts all of it in one React context; version B puts it in a Zustand store and has each component select only its slice. The cart was updated three times:

JSX
// A: context
const { cart } = useContext(AppCtx);                    // in Badge
const { user } = useContext(AppCtx);                    // in UserName — same context object
// B: store with selectors
const n = useStore(s => s.cart.length);                 // Badge subscribes to the cart length only
const name = useStore(s => s.user.name);                // UserName subscribes to the name only
Text
add to cart 3 times via one big context:        Badge 1×, UserName 1×, ThemeToggle 1×
add to cart 3 times via a store with selectors: Badge 1×, UserName 0×, ThemeToggle 0×

The three updates were batched into one render in both cases (chapter 22). But every consumer of a context re-renders whenever the context value changes, even ones that only read an unrelated field, and memo can't stop it because the change arrives through the context, not props. With selectors, a component re-renders only when its selected value changes. In a real app with hundreds of consumers, a single "global state" context turns every keystroke into an app-wide re-render. Use context for values that rarely change (theme, locale, the current user, injected services), split contexts by concern, and use a store with selectors (Zustand, Redux Toolkit's useSelector, Jotai atoms, signals) for frequently changing shared state.

Experiment 2: server state through a cache

Three components on one page each call useMenu() (the same queryKey: ["menu"], a 200 ms endpoint, staleTime: 30_000). Then the menu section is unmounted and mounted again:

Text
three components using the same query on first load → requests: 1 | 2 dishes | Idli
unmount and remount the menu within staleTime → requests: 1 | rendered from cache immediately: 2 dishes

Concurrent requests for the same key were deduplicated into one; the remount within staleTime rendered synchronously from the cache with no request (no spinner flash). After staleTime, a remount, a window refocus or a reconnect would show the cached data immediately and refetch in the background (stale-while-revalidate, the same idea as HTTP caching in chapter 19). The two numbers to tune per query are staleTime (how long data counts as fresh; default 0) and gcTime (how long unused data stays in memory; default 5 minutes).

Experiment 3: optimistic updates and rollback

A favourite button updates the cached favourites list before the server confirms (onMutate), rolls back if the request fails (onError), and refetches the truth either way (onSettled):

JSX
onMutate: async () => {
  await qc.cancelQueries({ queryKey: ["favs"] });                 // don't let an in-flight refetch overwrite us
  const prev = qc.getQueryData(["favs"]);
  qc.setQueryData(["favs"], old => [...(old ?? []), id]);         // optimistic
  return { prev };
},
onError: (_e, _v, ctx) => qc.setQueryData(["favs"], ctx.prev),   // roll back
onSettled: () => qc.invalidateQueries({ queryKey: ["favs"] }),

The component logged the favourites it rendered, with timestamps. Favouriting dish 1 (the server succeeds after 300 ms), then dish 2 (the server answers 500 after 300 ms):

Text
dish 1:  1244ms favs=[1]                                ← star shown instantly
         1553ms favs=[1]                                ← server confirmed; refetched list agrees
dish 2:  1893ms favs=[1,2]                              ← star shown instantly
         2192ms favs=[1]                                ← server failed: rolled back
         2196ms favs=[1] error: server said 500         ← error available to show the user
requests: POST /api/favs/1, GET /api/favs, POST /api/favs/2, GET /api/favs

The interface responded in the same frame as the click, which makes apps feel instant; the cost is that the UI briefly shows something that may not be true, so you need the rollback and a visible error message (a star that silently un-stars itself is confusing). Optimistic updates suit actions that almost always succeed and are cheap to undo (likes, reorders, toggles); a payment should show a pending state instead. React 19's useOptimistic does the same within a transition.

Try it yourself

  1. Split experiment 1's single context into three (cart, user, theme). Re-run it. Then explain why a context value created inline (value={{ cart, user }}) re-renders consumers on every parent render.
  2. Set staleTime to 0 in experiment 2, switch browser tabs away and back, and count requests. Which TanStack Query option controls that refetch?
  3. Make experiment 3's server slow (2 s) and click the favourite twice quickly. What happens without cancelQueries?
  4. Rewrite the order-status flags as a discriminated union in TypeScript and make the "error and done" state fail to compile.

Revision sheet: state management

Key ideas

  • Classify first: UI, form, shared client, server, URL and persistent state each have a natural home; ask who owns the truth.
  • Local by default, lift to the nearest common owner, share widely only when needed; never store derived data.
  • Context is dependency injection for values, not a performance-aware store: every consumer re-renders on value change; split contexts; keep values stable.
  • Stores: Redux Toolkit (actions, reducers, slices, middleware, DevTools), Zustand (minimal store with selectors), Jotai/Recoil-style atoms, signals (Angular, Solid, Preact, Vue refs), MobX observables; selectors limit re-renders.
  • Reducers and events: pure (state, action) → state; action logs enable testing, replay, undo and debugging.
  • State machines and statecharts (XState) make impossible states unrepresentable; discriminated unions do the same in types.
  • Server state: a cache keyed by query keys; dedupe, staleness (staleTime), garbage collection (gcTime), background refetch, invalidation after mutations, optimistic updates with rollback, pagination and infinite queries, retries with backoff, cancellation.
  • URL state for anything shareable; persistence with care (versioning, migrations, eviction).
  • Local-first and sync engines (Replicache/Zero, ElectricSQL, Triplit, CRDTs like Yjs/Automerge) keep a local database that syncs with the server.

Numbers to remember

  • Lab: one context change re-rendered all 3 consumers; selectors re-rendered 1.
  • TanStack Query defaults: staleTime 0, gcTime 5 minutes, queries retry 3 times, mutations 0.
  • 3 booleans = 8 combinations for 4 valid states.

Pitfalls

  • A single global context for everything; inline context values.
  • Copying server data into client stores; fetching in effects without cancellation or caching.
  • Storing derived or duplicated data; normalising too late (the same entity in two places, edited in one).
  • Optimistic updates without rollback or visible errors; optimistic updates for irreversible actions.
  • Putting shareable view state (filters, tabs) in memory instead of the URL.
  • Boolean flag soup for async status.

Glossary

  • Selector: a function picking the slice of state a component depends on.
  • Query key: the identity of a cached server resource (["dish", id]).
  • Stale-while-revalidate: show cached data immediately while refetching in the background.
  • Optimistic update: applying an expected server change locally before confirmation.
  • Normalisation: storing entities once by id and referencing them elsewhere.
  • CRDT: a conflict-free replicated data type that merges concurrent edits deterministically.