Workbench / Volume 2 Companion: The Web Frontend
V2·25
State Management
Companion to Volume 2, chapter 25: how classifying state, client-state tools and server state connect; new angles (state kinds as a kitchen's whiteboard, order slips, walk-in fridge and the menu board outside; a store as a noticeboard that rings a bell); what the chapter simplifies, measured: browser storage that throws in a sandboxed frame, stops at 5 MiB and tells only other tabs about changes; URL state, where ten filter changes with pushState made ten Back presses and the form disagreed with the address until it was synced; and preferences, where a theme kept in localStorage painted one wrong frame and a cookie the server reads painted none; the theory behind it; how Zustand's 20-line store works, and why setting an unchanged value still notifies everyone; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 25 has three strands. Classifying state: local and shared client state, server state, URL state, form state, persisted state, and making impossible states impossible. Client-state tools: context and reducers, Redux Toolkit, Zustand, signals and observable models, state machines, selectors. Server state: the cache, staleness and invalidation, optimistic updates, pagination, retries and cancellation, local-first sync.
The links worth remembering:
- Classification decides the tool. Once you know a piece of state is server state (a copy of the server's data), URL state (what screen this is), or a preference (persisted, maybe server-visible), the right home and the right tool usually follow. Most state bugs are a piece of state living in the wrong place, or in two places (drill D2).
- A store is a value plus a way to hear about changes. Redux, Zustand, the build's
store.tsand signals all expose "read the current value" and "tell me when it changes"; what differs is what counts as a change and who gets told (Code walkthrough, drill D4). - Where state lives decides who can see it, and when. The server sees cookies and the URL before the first byte; scripts see storage only after they run; other tabs see storage changes but not memory (Gaps 1 and 3).
Explain it differently
1. State kinds are a restaurant's information. The chef's mental note of what's on the stove is local state; the order slips on the rail are shared client state; the walk-in fridge's stock is server state (you only see a copy when you check); the menu board outside is URL state (anyone walking past sees the same thing); the regular's "usual" is a persisted preference.
2. Server state is a photograph of the fridge. It was true when you looked. Staleness is how old the photo is; invalidation is knowing when to take a new one; an optimistic update is writing "milk: 2" on the photo before you've checked the fridge.
3. A store is a noticeboard with a bell. Anyone can read the board; when it changes, the bell rings and everyone subscribed looks up. A selector is looking only at your own pinned note; a store that rings the bell when nobody changed anything wastes everyone's attention (drill D4).
4. URL state is a bookmark in a recipe book. The page number is the state: give it to someone and they open the same page; the Back button is flicking back through the pages you visited. Every bookmark you add is a page someone may have to flick back through (drill D1).
5. A reducer is a ledger. Instead of overwriting balances, you write entries ("order accepted", "order handed over") and the balance is the sum. You can replay, audit and test entries one at a time.
6. A state machine is a recipe's steps. You can't plate before you've cooked; the recipe says which step can follow which, so "plated but not cooked" can't happen.
7. Persisted preferences are a regular's usual. If it's written in the waiter's own notebook (localStorage), only that waiter knows, and only once they've arrived at the table; if it's on the booking (a cookie), the kitchen knows before the guest sits down (Gaps 3).
8. Local-first is everyone keeping their own copy of the menu draft. Each edits offline; when they meet, the copies are merged. The hard part isn't copying, it's merging.
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from Chromium, Node 22 and the build's stage 25 (exp/25), unless stated.
1. Browser storage is a convenience, not a store. The chapter lists localStorage among the places persisted state can live. Three things it doesn't promise, from one experiment:
sandboxed iframe, localStorage.setItem: ["SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag."]
localStorage quota: QuotaExceededError after 4 MiB-sized values and 1020 more KiB (5116 KiB of values; keys count too) | Failed to execute 'setItem' on 'Storage': Setting the value of 'k4' exceeded the quota.
storage event, tab that wrote: [] | other tab: ['theme=dark']
Merely reading localStorage throws in a sandboxed frame (embedding widgets, some previews, some in-app browsers), and private modes and blocked site data have thrown in other browsers. Writes throw once the origin has about 5 MiB, shared by every feature on the origin. And the storage event reaches other tabs, never the tab that wrote, so a page that wants every tab in step needs both its own update and the event (or a BroadcastChannel). Every access needs try/catch, a fallback for when it's missing, a size budget, and no assumption that what was written is still there. For anything that matters (a cart, a draft order), the server or IndexedDB with explicit error handling is the store; localStorage is a cache of preferences.
2. URL state: the address, the history and the form must agree. The build's kitchen filter lives in the URL (?show=Ready): bookmarkable, shareable, rendered by the server, and the same for all three views. Two decisions that the chapter's "put it in the URL" leaves open. Whether each change is a history entry:
10 filter changes with pushState: history.length 3 -> 13
10 filter changes with replaceState: history.length 14 -> 14
The build uses pushState because choosing another station's screen is a navigation people expect Back to undo. For a search box updated on each keystroke, the same choice would put a Back press behind every letter (drill D1). And keeping the controls in step with the address: after Back, the URL and the store change, but the form's radio buttons don't, unless something sets them (drill D2). The URL is also user input: the build parses show against the known screens and falls back to "all" (parseShow('?show=%3Cscript%3E') is '' in its tests), on the server and in the browser alike.
3. Where a preference lives decides whether the first paint is right. The usual way to remember a theme is localStorage plus a script that applies it. Stage 25 compares that with a cookie the server reads, frame by frame, on a device set to light with the visitor's choice of dark, CPU throttled 4×:
theme cookie, set by the server : 75 frames sampled | first frame [99, 'rgb(22, 19, 15)'] | frames in the wrong (light) theme: 0
theme localStorage, set by a module script : 76 frames sampled | first frame [107, 'rgb(255, 253, 248)'] | frames in the wrong (light) theme: 1, from 107 to 107 ms
A module script runs after the document is parsed, so the browser could paint once before it: one frame of the wrong theme, the "flash" people notice on dark-mode sites. A blocking inline script in the head avoids that but needs 'unsafe-inline' or a hash in the CSP. The cookie needs no script at all: the server writes data-theme into the first byte, the form works without JavaScript, and the cookie can be HttpOnly. Its costs: every page now varies by a cookie, so it must not be cached publicly without varying on it (the build's pages are no-store), and the cookie travels on every request. The general rule: state the server needs for the first render belongs where the server can see it.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
"localStorage is always there." |
It threw on read in a sandboxed frame and on write at 5 MiB. | Gaps 1 |
| "The storage event keeps all tabs in sync." | It fired in the other tab, not the one that wrote. | Gaps 1 |
| "Put filters in the URL and you're done." | Push or replace is a decision; controls must follow Back. | Gaps 2; drills D1, D2 |
| "Dark mode from localStorage is fine with a fast script." | A module script let one wrong frame through. | Gaps 3 |
| "Stores only notify when something changed." | Zustand's merge notified for an unchanged value. | Drill D4 |
| "Classifying state is a one-off exercise." | Each new feature adds state to place; the build's filter and theme were both new kinds. | Gaps 2–3 |
Theoretical gaps: the ideas behind the chapter
1. Single source of truth is normalisation. Each fact stored once, everything else derived, is database normalisation applied to the client: duplicates (the radio button and the URL) are denormalised copies that need an update rule, or they drift (drill D2). Derived values (visible = orders.filter(show)) are views, computed rather than stored.
2. Reducers are event sourcing in miniature. State as a fold over events (state = events.reduce(reducer, initial)) gives replay, time travel and testability; the build's server does the same with its order log. The cost is the same too: the event schema becomes a contract.
3. Server state is a cache, and caches have a consistency model. "Stale while revalidate" is eventual consistency; optimistic updates are writes that may be rolled back (like a transaction that might abort); invalidation by key is a cache-coherence protocol. Volume 3's distributed systems chapters give these their names.
4. Observers and the notification order problem. A subject notifying observers raises the same questions every time: are observers notified on every set or only on change (drill D4)? What if an observer changes the subject, or the observer list, during notification (Read it yourself Q2)? Glitch-free reactive systems (chapter 21's push-pull signals) are one answer; "notify after every set, let selectors filter" is another.
5. URL as a state serialisation format. A URL is a tiny, user-editable, server-visible, bookmarkable serialised state with a size limit and an encoding. Its design questions are a format's: which fields, defaults (omitted means "all"), versioning (old bookmarks must still parse), validation (it's user input).
6. CRDTs make merges automatic by restricting operations. Local-first sync needs merges that give the same result whatever order the replicas exchange changes. CRDTs (conflict-free replicated data types) guarantee this by using only operations that commute; the price is that some intentions (move this item, keep only one winner) need special types or lose information.
Applying it
Code walkthrough
Chapter Exercises P3 uses Zustand from React. Under the hook is a store small enough to read in a minute. Excerpts from Zustand 5.0.8, esm/vanilla.mjs and esm/react.mjs, installed from npm.
The store
const createStoreImpl = (createState) => {
let state;
const listeners = /* @__PURE__ */ new Set();
const setState = (partial, replace) => {
const nextState = typeof partial === "function" ? partial(state) : partial;
if (!Object.is(nextState, state)) {
const previousState = state;
state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
listeners.forEach((listener) => listener(state, previousState));
}
};
const getState = () => state;
const getInitialState = () => initialState;
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const api = { setState, getState, getInitialState, subscribe };
const initialState = state = createState(setState, getState, api);
return api;
};
The whole store: a variable, a Set of listeners, and setState. setState accepts a value or an updater function. If the result Object.is the current state, nothing happens. Otherwise an object is shallow-merged into a new object (unless replace is passed) and every listener is called with the new and previous state. There's no comparison of the merged contents: "changed" means "a different object was passed in", and the merge always makes a different object (drill D4). createState receives setState, getState and the API, which is how actions are defined inside the store.
The React hook
function useStore(api, selector = identity) {
const slice = React.useSyncExternalStore(
api.subscribe,
React.useCallback(() => selector(api.getState()), [api, selector]),
React.useCallback(() => selector(api.getInitialState()), [api, selector])
);
React.useDebugValue(slice);
return slice;
}
The React side is useSyncExternalStore (chapter 22's companion) with a selector applied to the snapshot. Every store notification calls every component's selector; React re-renders only the components whose selected value isn't Object.is the last one. That's why a selector returning a new object each time loops (Chapter Exercises P3), and why useShallow exists. The server snapshot is the initial state, so server rendering sees the store as created, not as changed.
Read it yourself
- With a store
{count: 1, show: 'Ready'}and one listener, how many times is the listener called bysetState({count: 1}), thensetState(s => s), thensetState(s => ({...s}))? - During one
setState, listener A subscribes a new listener C and unsubscribes listener B (subscribed after A, so not yet called). Which listeners run in that notification?
Debugging drills
D1. "The Back button doesn't work" on the menu search
The menu's search box now writes the query to the URL on every keystroke, so results can be shared. Users complain that Back "does nothing" after searching: they press it repeatedly and stay on the menu.
D2. After Back, the screen says one thing and the form another
On the kitchen display, a cook switches from "At the pass" to "New", then presses Back. The cards change back to the pass, and the address says ?show=Ready, but the radio button still shows "New".
D3. Preferences stopped saving, and then the page stopped working
A customer page caches recent orders in localStorage "to load faster", and stores the theme there too. For some customers, the theme stopped being remembered, and later the page threw on load and showed nothing.
D4. Every list re-renders when anyone touches the store
A Zustand store holds {orders, show, theme}. Components select slices, yet the profiler shows every subscriber's selector running, and some components re-rendering, whenever a button calls set({ show }) with the value it already has.
Career-oriented
Interview prep
Mid level
Q1. A list page has a filter, a sort order, a page number, an expanded row and a half-typed comment. Where does each live?
How to get there. For each, ask: should it survive a reload? Should a shared link reproduce it? Does the server need it to render? Who else reads it?
Q2. How would you remember a user's theme choice?
How to get there. Think about the first paint, users without JavaScript, other devices and the CSP.
Senior level
Q3. A kitchen opens the display in several tabs and devices. Each tab holds its own copy of the state and its own stream. What problems does that cause and what would you do?
How to get there. Think about connection limits, consistency between tabs, and duplicated work.
Q4. You inherit three views of one screen, each with its own copy of the data logic. How do you get them onto one store without breaking them?
How to get there. Think about the order of moves, and what proves each step safe.
Staff level
Q5. Set guidelines for state management across twenty frontend teams.
How to get there. Teams don't need one library; they need shared decisions about where state lives and how it's tested.
Q6. A product manager wants the kitchen display to work offline and merge with other devices later. How do you decide between a sync engine and building on the current store?
How to get there. Weigh what must merge, how conflicts are resolved, and what the team must own.