Workbench / Volume 2 Companion: The Web Frontend
V2·22
React
Companion to Volume 2, chapter 22: how React's fundamentals, hooks and rendering model connect; new angles (render as a waiter writing an order, commit as the kitchen cooking it, keys as table numbers, effects as standing arrangements with suppliers, Fiber as a cook who can put a dish down); what the chapter simplifies, measured: server rendering that escapes text but lets JSON in a script tag, a style url() and dangerouslySetInnerHTML through untouched; store updates that ignore startTransition and block for 140 ms where the same update in state blocks for none; and the price of React itself, 61 KB gzipped and about 100 ms of start-up script on a throttled CPU; the theory behind it; how the use-sync-external-store shim works, and why it lets six readers of one store commit six different values; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 22 has three strands. Fundamentals: components and JSX, props, state as a snapshot per render, events, lists and keys, composition. Hooks: useState and useReducer, effects, refs, memoisation, context and custom hooks, and subscribing to external stores. Rendering and modern React: render then commit, Fiber, concurrent rendering, transitions and Suspense, streaming SSR and hydration, Server Components, and actions.
The links worth remembering:
- A render is a calculation; a commit is an action. Rendering calls your components to work out what the screen should be, and may be repeated, paused or thrown away. Committing changes the DOM once. Everything that touches the outside world (subscriptions, requests, focus) belongs in commit-time code: effects, refs, event handlers.
- State is React's; everything else is outside. React can pause, replay and prioritise renders only for data it owns. Data that lives elsewhere (an EventSource,
localStorage, a store shared with non-React code) enters throughuseSyncExternalStore, which trades that flexibility for consistency (Gaps 2, Code walkthrough). - Identity drives everything. Keys decide which component instance is which;
===decides whether memo skips a component and whether a snapshot changed. Most React performance bugs and many state bugs are identity bugs (drills D3 and D4).
Explain it differently
1. Render is the waiter writing the order; commit is the kitchen cooking it. The waiter can tear up the slip and start again when the customer changes their mind, as often as needed, at no cost to the kitchen. Once the slip goes to the pass, the kitchen cooks it. A component that sends a request while rendering is a waiter who starts cooking at the table.
2. State is a photograph, not a live camera. Each render gets a snapshot of state. setCount(count + 1) three times in one handler adds one, because all three read the same photograph; setCount(c => c + 1) hands React an instruction to apply to whatever the newest photograph is (Chapter Exercises P1).
3. Keys are table numbers. When diners move, the waiter follows the table numbers, not the seat positions. Index keys are seat positions: insert a table at the front and every order is served to the wrong party.
4. Effects are standing arrangements with suppliers. "Deliver milk every morning" (subscribe) comes with "cancel when we close" (cleanup). Strict Mode is the manager who opens, closes and reopens the restaurant on day one to check every arrangement can be cancelled (drill D1).
5. Fiber is a cook who can put a dish down. The old reconciler was a cook who, once started, finished the whole banquet before looking up. Fiber's units of work let React stop between components, take an urgent order (a keystroke) and come back, or throw the half-made dish away if the order changed.
6. A transition is a "when you have a moment" order. The kitchen keeps it going but serves urgent orders first. It only works for orders the kitchen itself controls; an order that comes from an outside supplier's schedule (an external store) has to be dealt with right away (Gaps 2).
7. Hydration is moving into a furnished flat. The server's HTML is the furniture, already in place; hydration connects the electricity and plumbing (event handlers, state). If the study plan of the flat doesn't match the furniture (a mismatch), React has to throw things out and redo the room.
8. Server Components are a central kitchen. Some dishes are prepared once at the central kitchen and delivered ready to eat (server-only code, no JavaScript shipped); the restaurant only finishes what has to be done at the table (Client Components). The boundary is the delivery van: only serialisable things fit in it.
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from React 19.1.1, Node 22 and Chromium (exp/22).
1. Security: React escapes text, and that's all it promises. The chapter says text is escaped automatically, so {userInput} can't inject HTML. True, and easy to over-read as "React output is safe". A dish whose name, link and note are attacker-controlled, server-rendered with renderToString:
text child <p><img src=x onerror=alert(1)></p>
attribute <link rel="preload" as="image" href="/x.png"/><img alt="<img src=x onerror=alert(1)>" src="/x.png"/>
href with a javascript: URL <a href="javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')">Open</a>
dangerouslySetInnerHTML <div><img src=x onerror=alert(1)></div>
initial state, JSON.stringify in <script> <script>window.__STATE__ = {"note":"</script><script>alert(1)</script>"}</script>
style object with url() <div style="background-image:url(javascript:alert(document.cookie))"></div>
Text and attribute values are escaped, and React 19 replaces a javascript: URL in href with one that throws. Three things go through untouched. dangerouslySetInnerHTML is raw, as its name says. The initial-state pattern is the dangerous one: JSON.stringify doesn't escape </script>, so a note containing it ends the script element and starts the attacker's; the fix is to escape < as < when serialising (or put the JSON in a <script type="application/json"> and parse it, still escaping <). And a url() built from user input in a style object is emitted as written; modern browsers don't run javascript: URLs from CSS, but an attacker-chosen url() still makes every viewer's browser request whatever address the attacker likes (tracking, or leaking data in the URL), so URLs need validating whatever sink they go to. (React also added a <link rel="preload"> for the image without being asked: server rendering writes HTML you didn't write.) Chapter 28's Trusted Types and CSP are what catch these at the browser; review rules catch them earlier. The build bans dangerouslySetInnerHTML in its boundary check.
2. Transitions don't apply to external stores. The chapter presents useSyncExternalStore as "the correct way to subscribe to external stores" and transitions as the way to keep updates interruptible. Together they don't combine. A list of 400 rows, each taking 0.3 ms to render, updated inside startTransition, once from useState and once from a store read with useSyncExternalStore:
update inside startTransition, state: a 0 ms timer queued right after ran 1 ms later | long tasks: [] | rows show '1-0'
update inside startTransition, store: a 0 ms timer queued right after ran 146 ms later | long tasks: [140] | rows show '1-0'
The state version rendered in slices, yielding every few milliseconds: no long task, and the timer ran almost at once. The store version rendered all 120 ms in one go. That's by design: React can't pause in the middle of reading a store it doesn't own, because the store might change during the pause and different components would show different values (Code walkthrough shows exactly that happening). So React renders store updates synchronously, and startTransition around them is ignored. On the kitchen display, every snapshot from the SSE stream is a store update: the React view's first version blocked for 143 ms on 500 orders under a 4× CPU throttle (drill D2). The ways out are to keep store updates cheap (memoised children, small props), copy the store value into state where interruptibility matters (useDeferredValue on the result), or render progressively.
3. React's price is paid before the first update. The chapter covers React's update costs (re-rendering, memo, the compiler). The build measured the other half. The kitchen display's plain TypeScript version and its React version, the same features, measured by stage 22:
plain JavaScript for the display: 27 KB, 8 KB gzipped, 8 file(s)
react JavaScript for the display: 193 KB, 61 KB gzipped, 1 file(s)
And with 500 orders on a CPU throttled 4×, stage 18's measurement run three times on each view:
plain run 1: all 500 cards on screen after 0.80 s
plain run 1: while loading: 2 long tasks, longest 50 ms | worst animation frame: {'d': 60, 'blocking': 0, 'scripts': []}
react run 1: all 500 cards on screen after 0.91 s
react run 1: while loading: 2 long tasks, longest 102 ms | worst animation frame: {'d': 105, 'blocking': 53, 'scripts': ['http://127.0.0.1:18300/react-kitchen.js 100 ms (react-kitchen.js)']}
plain run 2: all 500 cards on screen after 0.70 s
plain run 2: while loading: 0 long tasks, longest 0 ms | worst animation frame: {'d': 53, 'blocking': 0, 'scripts': ['http://127.0.0.1:18300/kitchen.js 7 ms (kitchen.js)', 'Response.json.then 8 ms (lib.js)']}
react run 2: all 500 cards on screen after 0.93 s
react run 2: while loading: 1 long tasks, longest 126 ms | worst animation frame: {'d': 142, 'blocking': 77, 'scripts': ['http://127.0.0.1:18300/react-kitchen.js 105 ms (react-kitchen.js)']}
plain run 3: all 500 cards on screen after 0.66 s
plain run 3: while loading: 1 long tasks, longest 52 ms | worst animation frame: {'d': 72, 'blocking': 11, 'scripts': []}
react run 3: all 500 cards on screen after 0.91 s
react run 3: while loading: 1 long tasks, longest 104 ms | worst animation frame: {'d': 108, 'blocking': 56, 'scripts': ['http://127.0.0.1:18300/react-kitchen.js 104 ms (react-kitchen.js)']}
(Every run of both views also printed long tasks during updates: 0. A warm-up run, not shown, had a 108 ms idle-time task in the plain view, from stage 21's announcer warming Intl, and 161 ms for the React bundle: single runs on a shared machine are noisy, which is why the table repeats them.)
After three rounds of optimisation (drills D2 and D3) the React view's updates have no long tasks at all. Its worst frame is evaluating the bundle: 100–105 ms of script before any component runs, on every page load, on the kitchen's cheap tablet. That cost doesn't appear in React DevTools' profiler, which starts at the first render. It's often worth paying: a team that knows React, an ecosystem, components shared across many screens. But it's a cost to weigh per surface, and a reason to keep domain logic outside the framework (interview Q4 and Q5).
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "React output is XSS-safe." | Text and attributes are escaped; raw HTML, inline JSON and URLs are yours to handle. | Gaps 1; interview Q2 |
| "Wrap it in startTransition and it won't block." | Only updates to React state are interruptible; store updates render synchronously. | Gaps 2; drill D2 |
"useSyncExternalStore is just useEffect plus useState." |
That's the old shim, and it can commit inconsistent values; the built-in hook prevents tearing. | Code walkthrough |
"memo makes a list cheap." |
Only if props stay ===; one prop that changes for every row re-renders every row. |
Drill D3 |
| "getSnapshot can build an object each time." | It must return the same value while nothing changed, or React loops. | Drill D4 |
| "Strict Mode's double effects are a development quirk." | They rehearse what production remounts do; an effect without cleanup leaks there too. | Drill D1 |
Theoretical gaps: the ideas behind the chapter
1. Rendering as a pure function makes it schedulable. Because components are meant to be pure (same props, state and context give the same output, no side effects), React can call them any number of times, in any order, and discard results. Purity is what allows Strict Mode's double rendering, concurrent rendering and the compiler's memoisation; every impurity you add removes one of those options.
2. Reconciliation is a heuristic, not tree diff. The optimal edit distance between two trees costs O(n³). React's diff is O(n) because it assumes elements of different types produce different trees and uses keys to match children. The heuristic is why changing a component's type (or its key) throws away its state, and why keys must be stable.
3. Fiber is a reified call stack. Normal recursion keeps the work's state on the JavaScript call stack, which can't be paused. Fiber stores each unit of work as an object on the heap (a fiber with child, sibling and return pointers), so the "stack" can be paused, resumed, prioritised or abandoned: cooperative scheduling, as in an operating system without preemption (Volume 1's scheduling chapter).
4. Tearing is a consistency problem. When one render reads a mutable source at different moments, different parts of the UI reflect different versions: the same anomaly as a non-repeatable read in databases (Volume 3). React's answers mirror databases': own the data and version it (state, which concurrent rendering can snapshot), or read external sources under a lock-like rule (render synchronously, useSyncExternalStore).
5. Suspense is algebraic effects, approximated. A component that isn't ready "performs an effect" (throws a promise, or calls use) that a handler higher up (the Suspense boundary) catches, shows a fallback, and resumes rendering when the promise settles. Languages such as OCaml 5 and Koka support resumable effects natively; React approximates resumption by re-rendering from the boundary.
6. Hydration is replay; resumability is the alternative. Hydration re-runs the component tree on the client to rebuild state and attach handlers that the server already worked out, so the client pays to repeat the server's work. Resumable frameworks (Qwik) serialise enough of the application's state and handler locations into the HTML that the client can start from there without re-running. Server Components and selective hydration are React's ways of hydrating less.
Applying it
Code walkthrough
The build's React view reads its store through React's built-in useSyncExternalStore. Before React 18 had one, libraries used the use-sync-external-store shim, which still ships and is still installed by Redux, Zustand and others for compatibility. Reading it shows what the built-in hook had to fix. Excerpts from use-sync-external-store 1.5.0, cjs/use-sync-external-store-shim.development.js, installed from npm.
The hook
function useSyncExternalStore$2(subscribe, getSnapshot) {
// (a warning for React 18 alphas omitted)
var value = getSnapshot();
if (!didWarnUncachedGetSnapshot) {
var cachedValue = getSnapshot();
objectIs(value, cachedValue) ||
(console.error(
"The result of getSnapshot should be cached to avoid an infinite loop"
),
(didWarnUncachedGetSnapshot = !0));
}
cachedValue = useState({
inst: { value: value, getSnapshot: getSnapshot }
});
var inst = cachedValue[0].inst,
forceUpdate = cachedValue[1];
useLayoutEffect(
function () {
inst.value = value;
inst.getSnapshot = getSnapshot;
checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
},
[subscribe, value, getSnapshot]
);
useEffect(
function () {
checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
return subscribe(function () {
checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
});
},
[subscribe]
);
useDebugValue(value);
return value;
}
Every render reads the store directly (getSnapshot()), and in development reads it twice to check that two reads in a row give the same value: the source of the warning in drill D4. The value is remembered in a mutable box (inst) held in state, and the only reason for the state is forceUpdate: setting it to a new object makes React re-render. Two effects keep things right. The layout effect runs after every commit, before paint, and checks whether the store changed between render and commit; the passive effect subscribes, and every notification checks again. The design is sound in synchronous React: render and commit happen in one go, so the value read in render is still current at commit, or the layout effect catches it before anyone sees.
Checking for a change, and the server
function checkIfSnapshotChanged(inst) {
var latestGetSnapshot = inst.getSnapshot;
inst = inst.value;
try {
var nextValue = latestGetSnapshot();
return !objectIs(inst, nextValue);
} catch (error) {
return !0;
}
}
function useSyncExternalStore$1(subscribe, getSnapshot) {
return getSnapshot();
}
// …
shim =
"undefined" === typeof window ||
"undefined" === typeof window.document ||
"undefined" === typeof window.document.createElement
? useSyncExternalStore$1
: useSyncExternalStore$2;
exports.useSyncExternalStore =
void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
"Changed" means not Object.is, and a getSnapshot that throws counts as changed, so the re-render surfaces the error inside React. On the server there are no effects and no updates, so the shim just reads the value. The last line is the important one: when React has its own useSyncExternalStore (18 and later), the package hands that over and the shim's code never runs.
Read it yourself
- Copy the shim's hook into a React 19 app so it runs. Render six components that read the same store, with 60 slow components (0.3 ms each) between each pair, and start a re-render inside
startTransitionwhile a timer changes the store every 10 ms. Record what the six readers show at commit, in a layout effect, and in the DOM 1.5 s later. Then do the same with React's built-in hook. - In Node, with React 19.1.1 installed, is
require('use-sync-external-store/shim').useSyncExternalStorethe shim's function or React's?
Debugging drills
D1. The server shows two streams per kitchen tablet
The kitchen server's metrics show twice as many open SSE streams as tablets, and after a day the count is still climbing; the 500-stream cap from stage 17 starts refusing tablets. The React view opens its stream in an effect: useEffect(() => { new EventSource(url) }, []). A colleague says it's Strict Mode and only happens in development.
D2. startTransition didn't help
On 500 orders, every snapshot from the stream blocks the display for over 100 ms on the kitchen tablet. A developer wraps the store's updates in startTransition, then wraps the list in useDeferredValue(state.orders). The profiler still shows long tasks: 143 ms before, 146 ms after.
D3. A long task every 15 seconds
The display is smooth when orders arrive, but every 15 seconds the performance panel shows a 55 ms task, and the Performance Monitor shows every ticket re-rendering although Ticket is wrapped in memo. The parent passes now (refreshed every 15 s so lateness updates) to every ticket, which works out its own minutes waiting.
D4. "Maximum update depth exceeded" after a small refactor
The React view rendered fine with useSyncExternalStore(store.subscribe, () => store.count). A refactor to show two numbers changed it to () => ({ count: store.count, late: store.late }). Now the screen is blank and the console shows Maximum update depth exceeded.
Career-oriented
Interview prep
Mid level
Q1. When would you use useSyncExternalStore rather than useState plus a subscription in useEffect?
How to get there. Think about the first render, about two components reading the same source, and about what happens during a concurrent render.
Q2. Is it safe to render user-provided content in a React app?
How to get there. List every way user data reaches the page: text, attributes, URLs, raw HTML, styles, data embedded for hydration. Say which React handles.
Senior level
Q3. A React dashboard gets a server-sent event every second and the UI stutters on each one on low-end hardware. How do you diagnose and fix it?
How to get there. Measure before changing anything: which task is long, what's in it (render, commit, layout, your own code), and how much of the screen actually changes per event.
Q4. Your team has a working kitchen display in plain TypeScript. A new lead wants to rewrite it in React. How do you decide?
How to get there. Separate what React offers (a component model, an ecosystem, hiring) from what it costs (bytes, start-up, a dependency's upgrade cycle), and from what doesn't change (the domain logic).
Staff level
Q5. Design a frontend so that the business logic will outlive the UI framework.
How to get there. Think about which code changes when React is upgraded or replaced, and which shouldn't.
Q6. Your organisation has thirty React applications. Propose how to adopt the React Compiler.
How to get there. The compiler only helps code that follows React's rules, and it changes when things re-render. Think about finding rule-breaking code, rolling out safely, and proving the benefit.