Workbench / Volume 2 Exercises: The Web Frontend
V2·22
React
Exercises for Volume 2, chapter 22: the React mental model, components, JSX, props, state, events, lists and keys, composition, the hooks (useState, useReducer, useEffect, useRef, useMemo, useCallback, useContext, custom hooks), render/reconcile/commit, Fiber, performance controls, concurrent rendering, transitions, Suspense, streaming SSR, Server Components and the server/client boundary, hydration, actions and forms, error boundaries, the React Compiler, View Transitions, fragment refs and Trusted Types. 10 theory questions, 10 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
Same four sets and the same locking. The measured exercises use React 19.3.1 with react-dom in Node 22 and jsdom (rendered with act, the way React's own tests run) and the server renderer's streaming API. Every quoted output is real. Four of them catch people out: P1's three setN(n + 1) calls add only 1; P4's effect with an object dependency ran on every render; P8's form kept the user's invalid input only until React reset the form; and P9's error boundary ignored an error thrown in a click handler.
The chapter's lab measured re-render counts with and without memo, batching, Strict Mode's double effects, the fetch race in an effect and useDeferredValue keeping typing responsive. The exercises build on those without repeating them.
The running example is TiffinBox's React customer app: the kitchen page, the cart and checkout.
Coverage map.
| Chapter component | Exercises |
|---|---|
| mental model, components, JSX, props | T1 |
| state, snapshots, batching, useState vs useReducer | T2, P1, P2 |
| events | T2, P1 |
| lists, keys, resetting state with keys | T3, P3 |
| composition and children | T3 |
| useEffect, cleanup, dependencies, "you might not need an effect" | T4, P4 |
| useRef, useMemo, useCallback, useContext, custom hooks | T5, P5, P6 |
| render, reconcile, commit, paint; Fiber; performance controls; the React Compiler | T6, P6 |
| concurrent rendering, transitions, Suspense | T7, P10 |
| streaming SSR, hydration | T8, P7 |
| Server Components, server/client boundaries | T9 |
| actions and forms (useActionState, useOptimistic, useFormStatus) | T10, P8 |
| error boundaries | T10, P9 |
| View Transitions, fragment refs, Trusted Types | T10 |
Theory
T1. The mental model
- Explain "a component is a function from props and state to a description of UI" and why React components must be pure during render (same inputs → same output, no side effects). What breaks if a component mutates a prop, writes to a global during render, or reads
Math.random()orDate.now()directly? - What does JSX compile to (
jsx(type, props, key)), and what are the JSX rules (one root or a fragment,className,htmlFor, camelCase events and styles,{}for expressions,&&pitfalls with0)? - Props vs state: give the rule for what is a prop, what is state, and what is neither (derived), using the dish card and the cart.
T2. State, snapshots and batching
- P1: a button calling
setN(n + 1)three times moved the counter from 0 to 1; threesetN(m => m + 1)calls then moved it to 4. Explain state as a snapshot per render, the update queue, and when to use the updater form. - The lab showed three setters in one click render once. What is automatic batching (since React 18), and when do you need
flushSync(rarely: measuring DOM right after an update, focus management with third-party code)? useStatevsuseReducer: when does a reducer help (several related values, complex transitions, testability), and how does a discriminated-union action type (chapter 16) make the cart reducer safer?
T3. Lists, keys, composition
- P3 rendered
<Note dish={dish} />whose state was initialised fromdish: switching from dosa to idli kept "note for dosa"; withkey={dish}it showed "note for idli". Explain React's identity rules (same type at the same position keeps state), and thekeytrick to reset state. - Why is
useEffect(() => setNote('note for ' + dish), [dish])the wrong fix for P3? What are the alternatives (key, derive, store by id, "adjusting state during render")? - Explain
childrenand render props versus props for configuration, and whencloneElementorChildren.mapare a smell.
T4. Effects
- What is an effect for (synchronising with an external system: subscriptions, timers, DOM APIs, non-React widgets, network connections), and what is it not for (deriving state, handling user events, fetching data when a framework or cache can, resetting state on prop change, chaining state updates)?
- P4: an effect with a dependency array of
[opts], whereopts = { kitchen: 42 }is created during render, ran 6 times in 1 mount + 5 re-renders; with[opts.kitchen]it ran once. Explain dependency comparison (Object.is), and the fixes. - The lab's Strict Mode test showed connect → disconnect → connect in development. Write the cleanup for: a WebSocket/SSE connection, an interval, a
resizelistener, a fetch (abort), and a third-party map widget.
T5. Refs, memoisation, context and custom hooks
useRefholds a mutable value that doesn't trigger renders. Give three uses (DOM nodes for focus/measure, timer ids, the latest value for a callback) and the rule about reading or writingref.currentduring render.- P5: a memoised consumer of a context whose value was
value={{ cart }}re-rendered on all 5 unrelated parent updates; with auseMemo'd value, 0. Explain why context bypassesmemo, and the patterns for performant context (memoised values, splitting contexts, separating state and dispatch, selectors via external stores). - Write the rules of hooks, and a custom hook
useOrderStatus(orderId)that encapsulates SSE, reconnection status and cleanup. What makes a good custom hook (named for its purpose, not "useEffectOnce"; returns domain values)?
T6. Rendering, Fiber and performance
- Walk through render → reconcile → commit → paint for adding a dish: what runs in each phase, which phases can be interrupted, and where effects, layout effects and refs run.
- What is Fiber (a linked tree of units of work with priorities), and what does it make possible (interruptible rendering, prioritised updates, Suspense)?
- The performance toolbox:
memo,useMemo,useCallback, keys, splitting components, lifting content up ("children as props" so a stateful wrapper doesn't re-render its children), virtualisation, transitions, and the React Compiler. With the Compiler stable (2025), which of these should you still write by hand?
T7. Concurrent rendering, transitions and Suspense
- Explain urgent vs transition updates (
startTransition,useTransition'sisPending,useDeferredValue), and choose for: typing in search, switching menu tabs, applying a filter, navigating to a kitchen page, updating a live order counter. - How does Suspense work (a component "suspends" by throwing a promise or calling
use(promise); the nearest boundary shows its fallback), and how do you place boundaries (per page section, not one spinner for everything; nested; avoiding "popcorn" UI)? - Why do transitions keep the old UI visible instead of showing a fallback again when navigating (and what is
useTransition+ Suspense's "receding" behaviour)?
T8. Streaming SSR and hydration
- P7 streamed a page with
renderToPipeableStream: the shell with the fallback (219 bytes) arrived at +8 ms, and the menu HTML plus an inline script that swaps it in arrived at +308 ms when the data resolved.renderToStringon the same tree returned in 8 ms with only the fallback. Explain streaming SSR, why it improves TTFB and FCP, and whyrenderToStringis legacy. - P7's hydration test: server-rendered "Ordered at 12:41:07", client rendered "12:41:09": React reported a recoverable error "Hydration failed because the server rendered text didn't match the client…" and re-rendered the tree on the client. What causes mismatches (time, locale, random IDs,
typeof windowbranches, browser extensions), and how do you fix each (useId, passing server values,suppressHydrationWarning, client-only effects)? - What is selective hydration (Suspense boundaries hydrate independently, and user interaction prioritises the boundary being clicked)?
T9. Server Components and the server/client boundary
- What are React Server Components (components that run only on the server or at build time, can be
asyncand read data directly, send a serialised description to the client, and add no JavaScript to the bundle), and how do they differ from SSR? - What does
'use client'mark (a boundary: this module and its imports are client components), and what can cross the boundary (serialisable props: strings, numbers, plain objects, arrays, Dates, Promises, Server Functions; not functions, classes, or non-serialisable values)? Where do you put the boundary on the kitchen page? - What are Server Functions (
'use server'), what security rules apply to them (they're public endpoints: validate input, check auth, never trust the client), and how do they relate to forms?
T10. Actions, forms, error boundaries and new APIs
- P8 used
useActionStatewith<form action={action}>:pendingwas true while the action ran, the state updated withcount=2, and a second submit with qty 9 returnederror="Max 5 plates per dish". But the input then showed "2" again: React reset the form after the action. Explain actions,useActionState,useFormStatus, the automatic form reset, and how to keep the user's input on validation errors. - P8's
useOptimisticshowed the favourite heart filled immediately (♥) and reverted (♡) when the save failed. How do optimistic updates work in React 19, and what must the UI do on failure besides reverting? - P9: an error boundary caught a render error; an error thrown in a click handler reached the window's error event while the boundary kept showing its children; an async error was caught only after being re-thrown during render via state. Explain what boundaries catch, where to place them, and what to do with handler and async errors. Then describe View Transitions, fragment refs and Trusted Types support in one sentence each.
Programming exercises
P1. Snapshots and the update queue
Write a counter with two buttons: one calls setN(n + 1) three times, the other setN(m => m + 1) three times. Predict, then render it (in a browser, or with jsdom and act) and record the results. Then add a setTimeout(() => setN(n + 1), 1000) button, click it three times quickly, and explain the result.
P2. The cart as a typed reducer
Implement the cart with useReducer and a discriminated-union action type: add, remove, setQuantity (1–5, 0 removes), setNote, applyCoupon, clear. Derive totals in paise (subtotal, discount, GST at 5%, delivery fee, total) with pure functions. Unit-test the reducer and the totals without rendering, including property-based tests (fast-check: totals are never negative, removing everything gives zero).
P3. Reset state with keys
Build a DishNoteEditor whose note state is initialised from the dish (useState('note for ' + dish)), and render it for a selected dish. Switch dishes and record what it shows without and with key={dish}. Then implement the "notes per dish survive switching" version by storing notes by id in the parent.
P4. Effects with object dependencies
Render a component with two effects, one depending on [opts] where opts = { kitchen: 42 } is created in render and one on [opts.kitchen]; re-render the parent five times and count effect runs. Then make the object-dependency effect fetch the menu and set state, observe the infinite loop (with a guard), and fix it three ways.
P5. Context that doesn't re-render everything
Create a CartContext and a ThemeContext provided by the app root, with consumers wrapped in memo. Change unrelated root state five times and count consumer renders with value={{ cart }} versus a memoised value. Then split cart state and dispatch into two contexts and show that an "Add" button (dispatch only) no longer re-renders when the cart changes.
P6. Profile and fix a slow menu
Build a kitchen page with 300 dish cards, a search box and a cart drawer. Use the React DevTools Profiler to record typing "paneer": find what renders per keystroke and the commit times. Fix it in order: move state down, memo on DishCard (and stable callbacks), useDeferredValue for the list (the lab), virtualisation, then try the React Compiler instead of manual memo. Record commit times after each step.
P7. Stream a page, then break hydration
Using renderToPipeableStream, render a kitchen page whose menu suspends on a 300 ms data promise; log each chunk's arrival time and contents. Compare with renderToString. Then server-render a component showing the current time, hydrate it with a different time on the client, and record what React reports and what the DOM ends up showing. Fix the mismatch.
P8. Form actions, pending state and optimistic UI
Build "Add to cart" as a form with useActionState (server validation: max 5 plates per dish), a submit button that shows pending state with useFormStatus, and a favourite button with useOptimistic whose save can fail. Record the state timeline, including what happens to the input after a validation error. Then fix the input reset.
P9. What error boundaries catch
Wrap three components in an error boundary: one that throws during render, one that throws in a click handler, and one whose promise rejects in a handler and stores the error in state then throws it during render. Record what the boundary shows in each case and where the handler error goes. Then add react-error-boundary with a reset button and report errors with onCaughtError.
P10. Transitions for tab switching and navigation
Make the menu category tabs render a heavy panel (500 dishes). Switch tabs with a plain setTab and with startTransition, measuring the time from click to the tab's selected state appearing, and show isPending as a dimmed panel. Then add Suspense to the panel's data and check that during a transition the old panel stays visible instead of a fallback.
Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–22)
C1. The kitchen page in React, end to end
Build the kitchen page with Server Components (or a framework with loaders) for the kitchen, menu and reviews; client components for tabs, quantity steppers, favourites and the cart drawer; streaming with Suspense boundaries per section; form actions for add-to-cart with validation and optimistic quantity updates; error boundaries per section; accessibility to WCAG 2.2 AA (chapter 20); good Core Web Vitals (chapter 18: LCP image priority, no CLS from streaming, INP < 200 ms on a mid-range phone); and HTTP caching for the menu data (chapter 19). Write Playwright tests with role-based locators and axe.
Combines: HTTP caching (ch 19), rendering and Core Web Vitals (ch 18), accessibility (ch 20), UI architecture (ch 21), TypeScript and Zod (ch 16) and this chapter.
C2. Live order tracking with React and SSE
Build the order tracking page in React: useOrderStatus (T5) over SSE with reconnection and Last-Event-ID (chapter 17, 19), a status timeline, an accessible live region (chapter 20), a map component wrapped with a ref and cleanup (T4), a fallback poll if SSE fails, error boundaries, and tests that drive SSE events through Playwright routes. Make sure Strict Mode shows exactly one connection.
Combines: SSE and real-time transport choice (ch 17, 19), accessibility live regions (ch 20), UI architecture (ch 21) and this chapter's effects, refs and custom hooks.
C3. Migrate a class-component cart to modern React
An old cart is written with class components, componentWillReceiveProps, a mixin-style higher-order component for analytics, setState callbacks, and string refs. Migrate it to function components with hooks, a typed reducer (P2), context split by update frequency (P5), effects only for external sync (T4), React 19 APIs (ref as a prop, actions for checkout), and the React Compiler, keeping behaviour identical (characterisation tests first). Measure bundle size, render counts and bugs before and after.
Combines: Volume 1's refactoring and testing discipline (ch 01, 10), TypeScript (ch 16), UI architecture's incremental migration (ch 21's C2) and this chapter.
What the chapter leaves out
Testing React components
React Testing Library (with Vitest or Jest) tests components the way users use them: render, find elements by role/label/text (getByRole('button', { name: 'Add Paneer thali to cart' })), interact with user-event, and assert visible results, avoiding implementation details (state, internal methods). Async UI uses findBy* and waitFor; network is mocked with MSW. Hooks are tested with renderHook; reducers and pure functions directly (P2). Playwright component testing and Storybook interaction tests (chapter 21's gaps) cover browser-level behaviour. Chapter 26 covers frontend testing in depth.
Data fetching libraries and framework loaders
React's documentation discourages hand-written fetching effects (the lab's race, P4's loop). Use TanStack Query or SWR for client-side server state (caching by key, deduplication, background refresh, retries, pagination, optimistic updates, invalidation), or framework data APIs: Next.js Server Components and fetch caching, React Router/Remix loaders and actions, TanStack Router loaders. These integrate with Suspense and streaming. Chapter 25 compares state management approaches; chapter 24 covers full-stack frameworks.
Portals, refs to imperative APIs and integrating non-React code
createPortal(children, domNode) renders into another DOM node (modals, toasts, tooltips escaping overflow: hidden) while keeping React context and event bubbling through the React tree. useImperativeHandle exposes a limited imperative API from a component (ref.current.focusFirstError()). Integrating non-React widgets (maps, charts, rich text editors) uses a ref to a container, an effect to create and destroy the widget, and effects to push prop changes into it, with care not to let React and the widget both manage the same DOM. useSyncExternalStore connects external mutable stores (browser APIs, Redux-style stores) safely with concurrent rendering (no tearing).
React Native and React on other renderers
React's model is renderer-independent: React Native renders to native iOS and Android views (with its New Architecture: Fabric renderer, TurboModules, JSI), Expo provides the tooling, and React Native for Web shares code with the browser; other renderers target canvas and 3D (react-three-fiber), PDFs (react-pdf), terminals (Ink) and email (react-email). Skills transfer, but platform APIs, styling and performance differ. The mobile volume covers React Native.
Security in React apps
React escapes text by default, so {userInput} can't inject HTML; the risks are the escape hatches: dangerouslySetInnerHTML (sanitise with DOMPurify or use Trusted Types), href={userUrl} (javascript: URLs: React 19 blocks them with a warning, but validate schemes anyway), spreading untrusted props onto elements, server-side rendering of untrusted data into <script> tags (serialise safely), and Server Functions as public endpoints (T9). Dependency supply-chain risk (npm) applies too. Chapter 28 covers frontend security.
Senior exercises
S1. Set React standards for four teams
Write the team's React guidelines: TypeScript settings, component and hook conventions, where state lives (server cache, URL, local, global store), effects policy, data fetching approach, error and loading boundaries, accessibility requirements, testing expectations, performance practices with the React Compiler, folder structure (chapter 21), and lint rules that enforce them.
S2. Review a React pull request
A PR adds a kitchen search page: useEffect(() => { fetch('/api/search?q=' + q).then(r => r.json()).then(setResults) }, [q]) on every keystroke; results.map((r, i) => <Result key={i} … />); a const options = { sort: 'rating' } passed to a child's effect dependency; value={{ user, setUser }} on a context at the root; <div onClick> cards; dangerouslySetInnerHTML={{ __html: r.highlight }} for highlighted matches; and no loading or error states. Write the review.
S3. Plan the adoption of Server Components
TiffinBox's React SPA (client-rendered, 1.2 MB of JavaScript) has poor LCP on mobile. Leadership asks whether to move to Next.js App Router with Server Components. Write the plan: expected benefits (with how you'll measure), costs and risks (team learning, hosting, caching complexity, library compatibility, vendor coupling), alternatives (SSR with React Router framework mode, static pre-rendering, just optimising the SPA), migration path, and a go/no-go criterion.
S4. Debug "the cart sometimes shows the wrong total"
Users occasionally report the cart total briefly showing a wrong amount after changing quantities quickly, and twice a support ticket showed an order charged at an old price. Investigate the React and system causes (stale closures, effects deriving state, optimistic updates racing, out-of-order responses, caching), describe how you'd reproduce each, and design the fixes.
S5. Teach React's model in one diagram and four demos
Prepare a 20-minute session for backend engineers moving to frontend: one diagram of state → render → reconcile → commit → effects, and four live demos chosen from this chapter's outputs. End with five rules.