Volume 2 Exercises: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Exercises: The Web Frontend

V2·25

State Management

Exercises for Volume 2, chapter 25: classifying state (UI, form, URL, client, server, session, derived) and where it should live; client state tools (context, reducers, Redux Toolkit, Zustand, signals, observable models, state machines); and server state as a cache: staleness, invalidation, optimistic updates, pagination and infinite scrolling, retries, cancellation, and local-first sync engines. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~13 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use Redux Toolkit 2.14 with react-redux 9.3, Zustand 5.0.16, TanStack Query 5.105 (query-core, driven directly in Node), XState 5.33 and React 19.3.1 in jsdom. Every quoted output is real. Four of them are traps:

  • P2: a plain filter selector re-rendered on every unrelated Redux update, and Redux warned about it.
  • P3: a Zustand selector returning a new object hit "Maximum update depth exceeded" after 55 renders.
  • P5: TanStack Query retries 3 times in the browser (failing after about 7 s) but 0 times on the server.
  • P8: a state machine kept a stale error in its context after it succeeded.

The chapter's lab measured one big context against a store with selectors (badge 1×, unrelated consumers 1× vs 0×), query deduplication and caching (1 request for three components, no request on remount), and an optimistic favourite with rollback. The exercises build on those.

Coverage map.

Chapter component Exercises
kinds of state, and where state should live T1, P1
context T2, C1
reducers T2, P2
Redux and Redux Toolkit T3, P2
Zustand T3, P3
signals and observable models T4
state machines; impossible states T5, P8
the server-state cache, staleness T6, P4
invalidation T6, P4
optimistic updates T7, P6
pagination and infinite scrolling T7, P7
retries T8, P5
cancellation T8, P5
local-first and sync engines T9, P9

Theory

T1. Classify state first

  1. Classify each piece of TiffinBox's kitchen page state: whether the cart drawer is open, the search text, the selected category tab, the menu, the cart, the logged-in user, the checkout form draft, "is the kitchen open now", the theme, the order status stream, the scroll position, and an "added to cart" toast. Kinds: UI/local, form, URL, client (shared), server (cache), session, derived.
  2. For each kind, where should it live (component state, the URL, a form library, a client store, a server-state cache, cookies/session), and why does putting server data into a client store (dispatch(setMenu(data))) cause bugs?
  3. Explain "keep state as local as possible" and "lift state only as high as needed". What are the costs of too-global and too-local state?

T2. Context and reducers

  1. The lab: three cart additions via one big context re-rendered the badge, the user name and the theme toggle; via a store with selectors, only the badge. When is context the right tool (theme, locale, user, injected services), and how should a big context be split?
  2. Reducers as "changes as named events": why does dispatch({ type: 'dishAdded', dishId }) make state changes easier to reason about, log, test and replay than scattered setX calls?
  3. Combine useReducer and context for a feature-scoped store (the checkout wizard). When does this stop scaling and a library become worthwhile?

T3. Redux Toolkit and Zustand

  1. P2: a Redux Toolkit reducer written as s.items.find(…).qty++ produced a new state object and a new items array, reused the untouched item, and froze the old state (mutating it outside a reducer threw a TypeError). Explain Immer's structural sharing and why it matters for selectors and memo.
  2. P2: a component using useSelector(s => s.cart.items.filter(i => i.veg)) re-rendered on all 3 theme toggles (cart unchanged), and react-redux warned "Selector selectVegPlain returned a different result when called with the same parameters"; with createSelector it rendered 0 times. Explain selector equality and memoisation.
  3. P3: in Zustand 5, useCart(s => ({ count: s.count, total: s.total })) caused "The result of getSnapshot should be cached to avoid an infinite loop" and "Maximum update depth exceeded" after 55 renders; with useShallow it rendered once per change; a component selecting only s.user rendered 0 times during cart updates. Explain why, and compare Redux Toolkit and Zustand for TiffinBox.

T4. Signals and observable models

  1. How do signals (Angular, Preact signals, Solid, Vue refs, the TC39 proposal) handle shared state differently from a store with selectors (fine-grained subscriptions to exactly the values read; no selector equality to get right)?
  2. What are observable models (MobX: classes with observable fields, computed getters and actions; Valtio proxies), and their trade-offs (mutable-looking code, automatic tracking, magic)?
  3. Chapter 21's P2 found a naive signal library glitching (an effect saw ₹205, a total that never existed). Why do production libraries avoid glitches, and what rule follows for derived state (computed, not effects)?

T5. State machines

  1. P8: four booleans (isSubmitting, isAwaitingOtp, isError, isSuccess) allow 16 combinations, only 5 meaningful: 11 impossible states (e.g. submitting and succeeded). Explain "make impossible states impossible" with a discriminated union and with a state machine.
  2. P8's XState checkout machine moved idle → submitting → awaitingOtp → submitting → failed → submitting → succeeded, called placeOrder exactly once per submission (the 2nd and 3rd of a triple-click were ignored in submitting), and enforced at most 3 attempts. But the final context still had error: "bank timeout" after success. What's the bug and the fix?
  3. When are statecharts worth it (checkout, payment flows, onboarding, media players, drag-and-drop, connection management), and when is a reducer with a union type enough?

T6. Server state as a cache

  1. The lab: three components using the same query sent 1 request, and a remount within staleTime rendered from cache with 0 requests. Explain query keys, deduplication, staleTime, gcTime, and the triggers for background refetch (mount, window focus, reconnect, interval).
  2. P4: invalidating ['kitchen', 42] refetched the active menu query immediately, but the inactive reviews query was only marked stale (fetched again when it remounted). Explain prefix matching and why inactive queries aren't refetched.
  3. Choose staleTime and invalidation for: the menu, dish availability ("sold out"), the user's order history, a live order's status, the list of cities, and search results.

T7. Optimistic updates and pagination

  1. The lab's optimistic favourite: shown instantly, confirmed or rolled back, then refetched (onMutate, onError, onSettled). Write the full pattern for "change quantity in cart" including cancelling in-flight queries, snapshotting, rollback, and conflict handling with versions.
  2. P7: paging from page 1 to 2 without placeholderData: keepPreviousData, the UI went page 1 → no data, fetching → page 2 (a blank flash); with it, page 1 → page 1 (placeholder), fetching → page 2. Explain, and when to use each pattern: numbered pages, "Load more", infinite scroll.
  3. Infinite scrolling: useInfiniteQuery with cursor-based pages, refetching of all loaded pages, memory, accessibility (chapter 20), and when not to use it (footers, finding a specific item, SEO).

T8. Retries and cancellation

  1. P5: with the browser defaults, a failing query made 4 attempts (at 2, 1004, 3007 and 7011 ms: retries after 1, 2 and 4 s) and reached the error state after ~7 s; in Node (server), the same query made 1 attempt and failed after 1 ms, because the default retry is 0 on the server. What does this mean for users and for SSR prefetching?
  2. Which errors should be retried (network errors, 5xx, 429 with Retry-After) and which not (4xx, validation, 401)? Write a retry function and retryDelay with jitter.
  3. P5's cancellation: changing the search key from "pa" to "paneer" while "pa" was in flight aborted "pa" (the query function's signal fired) and the UI showed only "paneer". Explain how query libraries cancel (AbortSignal passed to queryFn) and what your queryFn must do for cancellation to reach the network.

T9. Local-first and sync engines

  1. What is local-first (the client holds a full or partial replica of the data, reads and writes locally, and syncs in the background; Linear, Figma, Replicache, Zero, ElectricSQL, PowerSync, Automerge/Yjs CRDTs), and what does it change compared with request/response server state?
  2. P9 merges the same cart edited offline on two devices. Compare last-writer-wins (whole cart), per-field LWW, and an operation log or CRDT. Which loses data?
  3. When is local-first worth its complexity for TiffinBox (the kitchen dashboard on flaky Wi-Fi, a menu editor, the customer cart), and what must stay server-authoritative (prices, stock, payments)?

Programming exercises

P1. A state inventory and a refactor plan

List every piece of state in your kitchen page (or a real app you work on): its kind (T1), current location, who reads and writes it, and the right location. Then refactor three misplaced ones: server data copied into a global store, a tab selection that should be in the URL, and a derived total stored in state.

P2. Redux Toolkit: Immer, freezing and memoised selectors

Create a cart slice with Immer-style reducers, dispatch an update, and check: whether the state object and array are new, whether an untouched item is reused, whether the old state is frozen. Then render a component with a plain filter selector and one with createSelector, dispatch three unrelated actions (theme toggles), and count renders and warnings.

P3. Zustand: the selector that loops

With Zustand 5, write a component selecting { count, total } as a new object, mount it, and record what happens. Fix it with useShallow and with two primitive selectors; count renders over three add calls, and check that a component selecting user doesn't re-render. Add persist middleware for the cart with a version and a migration.

P4. Query keys and invalidation

Using TanStack Query (React, Angular or query-core directly), create menu and reviews queries under ['kitchen', 42, …] with staleTime: 60_000. Unmount the reviews observer, invalidate ['kitchen', 42], and count fetches. Remount reviews. Then design the query key factory for the whole app and the invalidation map for each mutation.

P5. Retries and cancellation, measured

Make a query that always fails and record attempt times with the browser defaults; run the same in Node and compare. Then make a search query whose function logs start, abort and done, change its key while it's in flight, and check that the old request is aborted. Finally, add the retry/retryDelay policy from T8 and show a 404 fails immediately while a 503 retries.

P6. Optimistic quantity changes that survive rapid clicks

Implement "+" and "−" on cart lines with optimistic updates (T7), against a fake API with random 100–600 ms latency and a 10% failure rate. Click "+" five times quickly. Verify the final UI equals the server state, that a failure rolls back to the right value, and that the error is announced. Compare sending "+1" deltas versus absolute quantities, and serial mutation scopes versus parallel.

P7. Pagination without flashes, and Load more

Build the partner portal's paginated orders table (page in the URL) and the kitchen page's reviews "Load more". Record the UI states when moving from page 1 to 2 with and without keepPreviousData, prefetch the next page on hover of "Next", and make "Load more" accessible.

P8. A checkout state machine

Model checkout with XState (or a reducer with a discriminated union): idle, submitting, awaitingOtp, failed (with retry up to 3), succeeded. Triple-click submit, go through OTP, fail once, retry, and record states and calls. Find the stale-context bug, fix it, and write tests that generate paths through the machine.

P9. Merge an offline cart from two devices

Simulate two devices editing the same cart offline: A adds idli and changes dosa to 2; B changes dosa to 3 and removes vada. Merge with (a) whole-document last-writer-wins, (b) per-item LWW with timestamps, (c) an operation log replayed on the server with validation. Print the result of each and decide which TiffinBox should use.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–25)

C1. A state architecture for the customer app

Write and implement the state architecture for TiffinBox's React app: a classification table (T1), the server-state layer (query client defaults, key factory, invalidation map, SSE updates into the cache, retry and cancellation policies), client state (Zustand cart with persistence and migration, URL state for search and tabs), forms, a checkout state machine, cross-tab sync of the cart (BroadcastChannel: chapter 17), and testing at each layer. Measure re-renders and request counts on key pages before and after.

Combines: browser storage and BroadcastChannel (ch 17), HTTP caching and conflicts (ch 19), React rendering (ch 22), full-stack framework data loading (ch 24) and this chapter.

C2. The kitchen dashboard's offline-tolerant orders board

Make the kitchen dashboard keep working through Wi-Fi drops: the orders board reads from a local replica in IndexedDB updated by SSE, status changes are queued locally with idempotency keys and replayed on reconnect, conflicts (order cancelled by the customer, already accepted on another tablet) are shown clearly, and the UI shows connection state. Test it by cutting the network for 60 s during a busy simulated lunch.

Combines: IndexedDB and service workers (ch 17), SSE and HTTP semantics (ch 19), accessibility (ch 20), UI architecture (ch 21's C3), Angular or React (ch 22, 23), Volume 1's idempotency (ch 11) and this chapter's local-first ideas.

C3. Replace a homegrown global store

A legacy React app has a homegrown GlobalStore (one big context with 60 fields, mutations via setGlobal({ … }), server data, UI flags, form drafts and derived values all mixed). Plan and execute the migration to the architecture of C1 without a big bang, measuring render counts and bugs. Include how you'll keep both systems consistent during the transition.

Combines: UI architecture and incremental migration (ch 21's C2), React performance (ch 22's P6) and this chapter.

What the chapter leaves out

State in the URL, done well

URL state needs more than ?q=: parse and validate params (Zod), serialise arrays and dates consistently, keep URLs readable and stable for sharing and SEO, debounce writes while typing (history.replaceState vs pushState so Back doesn't step through every keystroke), and sync with the router's transitions. Libraries like nuqs (Next.js/React Router) and TanStack Router's typed search params make this type-safe. URL state is free persistence, sharing and Back support, so use it more than you think.

Forms as state

Form state has its own concerns: values, touched/dirty flags, validation (sync, async, cross-field), arrays of fields, submission state and server errors. Libraries (React Hook Form, TanStack Form, Formik; Angular reactive and signal forms: chapter 23) handle them with uncontrolled inputs or fine-grained subscriptions for performance. With React 19, server actions and useActionState cover simple forms (chapter 22's P8); complex forms still benefit from a form library plus a shared Zod schema with the server.

Devtools, debugging and state persistence

Redux DevTools (time travel, action log, state diff) works with Redux, Zustand (devtools middleware), NgRx and XState (inspect); TanStack Query Devtools show cache entries, staleness and fetches. Persistence choices: localStorage (small, synchronous, string-only), IndexedDB (large, async: via idb-keyval or query persisters), session storage for per-tab drafts, with versioning and migrations (P3) and care not to store secrets or personal data unnecessarily.

Real-time collaboration and presence

Collaborative editing (two kitchen staff editing a menu, a shared group order) needs presence ("Ravi is editing Paneer thali"), live cursors or locks, and conflict-free merging: CRDT libraries (Yjs, Automerge, Loro) with providers over WebSocket, or hosted services (Liveblocks, PartyKit), or server-ordered operations. Locks are simpler (one editor at a time per dish) and often enough; CRDTs are for true simultaneous editing. TiffinBox's "group order" (colleagues adding to one cart) is a good candidate for a CRDT list.

Server state beyond REST

GraphQL clients (Apollo, urql, Relay) provide normalised caches where entities are stored by id and updates to one entity update every query showing it, at the cost of cache configuration and complexity; Relay adds compiler-enforced data requirements per component. tRPC and RPC-style APIs integrate with TanStack Query. RTK Query (Redux) and SWR are alternatives to TanStack Query with similar ideas (keys, staleness, invalidation by tags).

Senior exercises

S1. Choose the state stack for TiffinBox's frontend

Write the decision: server state (TanStack Query vs RTK Query vs framework loaders/RSC), client state (Context only, Zustand, Redux Toolkit, Jotai, signals), forms, URL state, machines, and persistence. Consider the React customer app and the Angular partner portal, team size, SSR, DevTools, testing and bundle size. Give a recommendation and the rules that make it work.

S2. Review a state management pull request

A PR adds "group orders": a useEffect fetches the group cart every 2 seconds into a Zustand store with set({ groupCart: data }); members' additions call fetch('/api/group/add') and then set(s => ({ groupCart: { ...s.groupCart, items: [...s.groupCart.items, item] } })); the UI reads useGroup(s => ({ items: s.groupCart.items, total: s.total })); booleans isLoading, isError, isLocked, isSubmitted drive the screen; and the organiser's "submit order" button has no protection against double clicks. Write the review.

S3. Design caching and freshness rules for a multi-tab, multi-device user

A user has the TiffinBox app open in two browser tabs and on their phone. They add items, apply a coupon, change the address and place an order. Design how state stays consistent across tabs (BroadcastChannel, storage events, Web Locks for a leader tab: chapter 17), across devices (server sync, SSE/push), and what happens on conflicts (coupon used on the phone, cart changed in the other tab during checkout).

S4. Diagnose "the orders list shows yesterday's orders"

Partner portal users report that after leaving the dashboard open overnight, the orders list in the morning shows yesterday's orders until they reload. Investigate (query cache settings, SSE connection lost on sleep, service worker caching, staleTime: Infinity, background tab throttling), describe how to reproduce each, and design the fix.

S5. Teach "where does this state live?" in one exercise

Prepare a 20-minute workshop where engineers classify 15 pieces of state from a real TiffinBox screen, place them, and then see four failure demos from this chapter. End with five rules.