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

Workbench / Volume 2 Exercises: The Web Frontend

V2·21

UI Architecture

Exercises for Volume 2, chapter 21: UI as a function of state, components and their boundaries, composition, primitives, compound and headless components, design systems and design tokens, styling approaches, feature modules, domain boundaries and shared libraries, reuse, coupling and dependency direction, abstraction cost and premature abstraction, the three rendering strategies (rebuild, diff, fine-grained signals), keys and identity, and Web Components. 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. UI architecture is mostly judgement, so most exercises ask you to design, refactor and argue, then check the result with a small measurement. The measured ones run in Node 22, esbuild 0.25 and Chromium 153 (Playwright). Two outputs are worth knowing before you start: P2's naive signals produce a glitch (an effect sees a half-updated state), and P8 shows that a barrel file is free for a tree-shaking bundler but evaluates every module in Node and in tests.

The chapter's lab compared rebuild, diff and signals on a 1,000-row list (2,004 nodes touched vs 1 vs 1), showed index keys moving notes to the wrong dishes, and enforced dependency direction with a 20-line script. The exercises build on those.

TiffinBox's frontend is the running example: a menu, cart, checkout and kitchen dashboard built by four teams.

Coverage map.

Chapter component Exercises
UI = f(state); the three update strategies T1, P2
keys and identity T1, P3
components and component boundaries T2, P1
composition, primitives, compound components T3, P4
headless components T3, P5
design systems and design tokens T4, P6
styling approaches T5
feature modules, domain boundaries, shared libraries T6, P7, P8
reuse, coupling, dependency direction T7, P7
abstraction cost and premature abstraction T8, P1
Web Components: custom elements and shadow DOM T9, P9

Theory

T1. UI = f(state), and how frameworks apply it

  1. Explain "the UI is a function of the state" with TiffinBox's cart: what is the state, what is derived, and what goes wrong when the DOM itself is treated as the state (the "shopping list" problem from Start here)?
  2. The lab measured, for one row change in a 1,000-row list: innerHTML rebuild 2,004 nodes touched, focus lost, typed text lost; virtual-DOM diff 1 node, 1,000 comparisons, 0.44 ms; signals 1 node, 1 effect, 0.010 ms. Explain each strategy's costs and where each framework sits (React, Vue, Angular with signals, Svelte 5, Solid, Lit).
  3. Why are keys needed, and when are index keys safe? Explain why the lab's notes moved to the wrong dishes when Dosa was deleted.

T2. Component boundaries

  1. Give five heuristics for drawing component boundaries (single responsibility, a stable interface, where state lives, reuse, change together, testability) and apply them to the kitchen page: header, menu category tabs, dish card, quantity stepper, cart drawer, checkout summary.
  2. Explain presentational vs container (or "smart vs dumb") components, and how hooks/signals/services changed that split.
  3. What are the signs that a component is too big (a "god component") or too small (wrapper soup), and what should a good props interface look like (few props, domain names, no boolean explosions)?

T3. Composition, primitives, compound and headless components

  1. Explain composition with children/slots versus configuration props, using a Card that sometimes has an image, a badge, a footer with two buttons, and sometimes none.
  2. What is a compound component (e.g. <Tabs><Tabs.List><Tabs.Tab/></Tabs.List><Tabs.Panel/></Tabs>), how do the parts share state (context, injection), and what does it buy over a tabs={[…]} prop?
  3. What is a headless component or hook (Radix Primitives, React Aria, Headless UI, Angular CDK, TanStack Table, Downshift), and why do teams use headless libraries for complex widgets like comboboxes and menus?

T4. Design systems and tokens

  1. What does a design system contain (principles, tokens, components, patterns, content guidelines, accessibility rules, documentation, governance), and how is it different from a component library or a UI kit in Figma?
  2. Explain design token tiers: primitive (orange-500: #f5a623), semantic (color.action.primary, color.text.muted), component (button.primary.background). Why does theming (dark mode, a partner's white-label brand) depend on the semantic tier?
  3. How do tokens get from design to code (Figma variables, the W3C Design Tokens format, Style Dictionary or similar build steps producing CSS custom properties, TypeScript, Android XML and iOS Swift)?

T5. Styling approaches

  1. Compare global CSS with naming conventions (BEM), CSS Modules, CSS-in-JS with runtime (styled-components, Emotion), zero-runtime CSS-in-JS (vanilla-extract, Panda, StyleX), utility-first CSS (Tailwind), and shadow-DOM or framework scoping (Angular's emulated encapsulation, Vue/Svelte scoped styles) on scoping, performance, theming, server rendering and developer experience.
  2. Why did runtime CSS-in-JS fall out of favour with React Server Components and performance-focused teams?
  3. How do cascade layers (@layer reset, tokens, components, utilities, overrides: chapter 14) help a design system coexist with app styles and third-party CSS?

T6. Feature modules, domain boundaries and shared libraries

  1. Compare organising by type (components/, hooks/, services/, utils/) versus by feature (features/menu, features/cart, features/checkout, shared/). Why does organising by feature scale better for four teams?
  2. What is a feature's public API (its index.ts), and why do the lab's rules forbid reaching into features/cart/internal/ or shared → features imports?
  3. What belongs in shared/ (design system, utilities, API client, i18n) and what doesn't (business logic that belongs to one domain)? How do you stop shared/ from becoming a junk drawer?

T7. Coupling and dependency direction

  1. Explain afferent and efferent coupling, the stable dependencies principle (depend in the direction of stability), and apply it to app → features → shared.
  2. Checkout needs to clear the cart after a successful order, and the menu needs to show "In cart: 2" on dish cards. Give three ways to wire each (direct import, events, composition at a higher level, a shared store), with trade-offs.
  3. How do you break a cycle between two features?

T8. Reuse and premature abstraction

  1. "Duplication is far cheaper than the wrong abstraction" (Sandi Metz). Explain how the wrong abstraction happens (two similar components merged; the third use case adds a flag; the fourth another), and the rule of three.
  2. The chapter's "abstraction cost": every abstraction has a cost in indirection, learning, coupling and change friction. Estimate the cost of a GenericList component with 14 props used for the menu, orders, reviews and kitchen tickets.
  3. When is early abstraction right (design-system primitives, accessibility-critical widgets, security-critical code like sanitising, API clients)?

T9. Web Components

  1. What are custom elements, shadow DOM, templates and slots? P9 found: a page rule button { background: red } did not reach the button inside a shadow root; a CSS custom property --tb-accent did; ::part(label) styled it from outside; document.querySelector('tb-chip button') returned null. Explain each.
  2. P9's events: a custom event dispatched on the host reached document; one dispatched inside the shadow root with bubbles: true but not composed didn't; with composed: true it did, retargeted so event.target was tb-chip (and composedPath()[0] the inner button). What does that mean for component APIs?
  3. When are Web Components the right choice (design systems shared across React, Angular and plain pages; micro-frontends; embeddable widgets), and what are their weak spots (SSR with declarative shadow DOM, forms and accessibility across the shadow boundary, framework integration, styling)?

Programming exercises

P1. Split a god component

Take a 600-line KitchenPage component that fetches the kitchen and menu, manages tabs, the cart, a search box, favourites and a reviews carousel, with 22 state variables. Refactor it into feature components and hooks using T2's heuristics, without changing behaviour. Measure before and after: lines per file, state variables per component, props per component, test setup size, and how many files a "change the dish card layout" task touches.

P2. Build a signals library, and find the glitch

Implement two tiny reactive systems: (a) naive push: setting a signal immediately runs its subscribers, and computeds are effects that set signals; (b) pull with dirty marking: a set marks dependents dirty, effects are queued, and computeds recompute lazily when read. Model a cart where subtotal = qty × 100 and gst = qty × 5 both depend on qty, and an effect logs subtotal + gst. Set qty to 2 and record what the effect sees.

P3. Keys: reorder, insert, delete

Extend the lab's experiment 2: a list of dish rows, each with an uncontrolled notes input and a CSS transition on the quantity. Implement "move to top", "insert at top" and "delete" with three renderers: no keys (position), index keys, and id keys. Record which notes end up attached to which dishes, and whether focus and the transition survive.

P4. A compound Disclosure/Accordion component

Build <Accordion> with <Accordion.Item>, <Accordion.Trigger> and <Accordion.Panel> in your framework (React context, Angular DI or Vue provide/inject), supporting single and multiple expansion, controlled and uncontrolled modes, and correct accessibility (chapter 20's T9: a button in a heading with aria-expanded and aria-controls; a region panel labelled by the trigger). Use it for TiffinBox's FAQ and for the "nutrition info" section of a dish. Test keyboard and ARIA with role-based locators.

P5. Use a headless combobox, then style it as the design system's

Implement the "search dishes" combobox twice: once with a headless library (React Aria's useComboBox, Downshift, Headless UI, or Angular CDK's listbox/overlay) and once by hand. Compare lines of code, keyboard behaviour (Down/Up/Enter/Escape/Home/End, typeahead), screen-reader output with NVDA and VoiceOver, and behaviour on mobile (virtual keyboard, scrolling the list). Then style the headless one with your design tokens.

P6. A token pipeline with themes

Define TiffinBox's tokens in the W3C Design Tokens format: primitives (colours, spacing, radii, type scale), semantic tokens (text, surface, action, border, focus, status), and two themes (light, dark) plus a white-label "CorpCanteen" brand. Generate CSS custom properties and a TypeScript file with Style Dictionary (or a 50-line script), switch themes with data-theme, and add a CI check that every semantic text/background pair meets 4.5:1 in every theme (chapter 20's P7).

P7. Enforce boundaries with a real tool

Take the lab's sample project (or your app) and replace the 20-line script with dependency-cruiser or eslint-plugin-boundaries: rules for no upward imports (shared must not import features or app), features only through public index files, an allow-list of feature-to-feature dependencies (checkout → cart), no circular dependencies, and no imports of test utilities from production code. Run it in CI, then generate a dependency graph and find the most-depended-on modules.

P8. What a barrel file costs

Create shared/ui/index.js re-exporting five components (two of them with top-level side effects), import Button through the barrel and directly, and measure: the bundle size with esbuild (with and without "sideEffects": false), and the modules evaluated in Node (or your test runner). Discuss when barrels hurt (tests, dev servers, large libraries, cycles).

P9. A Web Component for the design system

Build <tb-chip> (a toggle chip like "Veg only") and <tb-qty> (a quantity stepper that participates in forms) as Web Components with shadow DOM. Verify: page styles don't leak in, design tokens (custom properties) do, ::part works, events are dispatched on the host, <tb-qty> submits its value with the form, and both have correct roles and names. Use them in a React page and an Angular page.

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

C1. Architect TiffinBox's frontend for four teams

Design the frontend architecture for the customer web app and kitchen dashboard, owned by four teams (Discovery, Ordering, Payments, Kitchen): folder and package structure (feature modules, shared design system, API client), dependency rules (P7), the design system's foundations (tokens P6, headless base P5, accessibility rules from chapter 20), state ownership (server data vs client state vs URL), rendering strategy per page (chapter 18's), how features communicate (T7), and the CI checks. Produce an architecture decision record and a diagram.

Combines: Volume 1's system design and ADRs (ch 00, 10), this volume's loading and rendering (ch 12, 18), CSS (ch 14), TypeScript (ch 16), networking (ch 19), accessibility (ch 20) and this chapter.

C2. Migrate a legacy jQuery page to components without a big bang

The kitchen dashboard is a 3,000-line jQuery page that treats the DOM as its state. Plan and execute an incremental migration to components: introduce a state store, render one region at a time from state (the strangler pattern), keep both working during the transition, add tests that protect behaviour, and measure bugs and performance before and after. Decide whether to target React, Angular or Web Components.

Combines: Volume 1's refactoring and testing practices (ch 01, 10), DOM APIs (ch 17), rendering (ch 18), accessibility (ch 20) and this chapter's UI = f(state), keys and boundaries.

C3. Design the kitchen dashboard's live order board

Build the kitchen's live order board: columns (New, Preparing, Ready), cards with timers, drag-and-drop with a keyboard and button alternative (WCAG 2.5.7), live updates over SSE (chapter 19) with reconciliation by order id (keys), optimistic moves with rollback on server rejection (409: chapter 19's T4), sounds and visual alerts for new orders, accessible announcements (chapter 20's T8), and good INP with 200 orders. Choose the state model and component boundaries.

Combines: real-time transports and HTTP semantics (ch 19), accessibility (ch 20), browser rendering and INP (ch 18), Web APIs (ch 17), Volume 1's concurrency and idempotency (ch 08, 11) and this chapter.

What the chapter leaves out

Micro-frontends

Micro-frontends split a frontend into separately built and deployed apps owned by different teams, composed at runtime (Module Federation in webpack/Rspack/Vite, single-spa, import maps, iframes or Web Components) or at the edge (server-side includes). They allow independent deploys and mixed stacks, at the cost of duplicated dependencies, inconsistent UX, cross-app state and routing complexity, larger bundles and harder performance tuning. Most organisations with fewer than a dozen frontend teams are better served by a modular monorepo with boundaries (P7, C1) and a shared design system. Chapter 30 covers monorepos and Module Federation.

Storybook, component documentation and visual testing

Storybook (and Ladle, Histoire) renders components in isolation with "stories" for each state, serving as documentation, a development sandbox, and a test harness: interaction tests (play functions), accessibility checks (the axe addon), and visual regression testing (Chromatic, Percy, Playwright screenshots) that catches unintended style changes across hundreds of components and themes. A design system without visual tests regresses silently when a token or shared style changes.

State machines and statecharts for UI logic

Complex component logic (a checkout with steps, retries, payment states; a media player; drag-and-drop) is clearer as an explicit state machine: finite states (idle, submitting, awaitingOtp, failed, succeeded), events and transitions, which makes impossible states impossible (no isLoading && isError). XState and statecharts add nesting, parallel states and visual tools; even a useReducer with a discriminated union (chapter 16) captures much of the benefit. Chapter 25 covers state management in depth.

Internationalisation architecture

Supporting English, Hindi, Telugu and Tamil shapes UI architecture: message catalogues with ICU MessageFormat (plurals, genders, selects), lazy-loading translations per route, Intl APIs for numbers (₹1,23,456 with Indian grouping), dates and relative times, right-to-left support for Urdu (logical CSS properties: chapter 14), components that tolerate 30–50% longer text, and locale in the URL (chapter 19's P4). Frameworks provide libraries (react-intl/FormatJS, Angular's i18n, vue-i18n), and the design system's components must accept translated labels rather than hard-coding text.

Architecture fitness functions and documentation

Beyond import rules (P7), teams encode architecture as fitness functions: automated checks for bundle size budgets per route, maximum dependency depth, banned APIs (no localStorage for tokens, no direct fetch outside the API client), performance budgets (chapter 27) and accessibility gates. Lightweight documentation (C4 diagrams, ADRs, a README per feature describing its public API and owner) keeps the architecture understandable as teams change.

Senior exercises

S1. Decide whether to build or adopt a component library

TiffinBox's design team wants a fully custom design system; engineering is split between building everything, adopting a styled library (MUI, Angular Material, Chakra), or a headless base (Radix/React Aria/Angular CDK) with custom styling. Write the decision: criteria, costs over two years, risks, and your recommendation.

S2. Review a "shared" component pull request

A PR adds shared/ui/SmartTable.tsx (900 lines) with props for sorting, filtering, pagination, row selection, inline editing, CSV export, column resizing, server-side data fetching from /api/orders, and a isKitchenMode flag that adds timers. It's used by the kitchen dashboard and the admin orders page. Write the review.

S3. Plan the design system's versioning and adoption

The design system package will be used by four teams and two apps. Define the versioning policy (semver, what counts as breaking: a token value? a prop rename? a DOM structure change?), the release process, deprecation strategy, codemods, how teams adopt updates (Renovate, a monorepo with one version), and how you'll measure adoption and health.

S4. Choose between signals and VDOM for a new app

A new TiffinBox "kitchen analytics" app will show live dashboards (dozens of charts and counters updated every second over SSE) and complex filters. The team knows React. Should they use React (with careful memoisation or the React Compiler), React with an external signals/store library, Solid, Svelte 5, or Angular with signals? Make the decision with criteria and a prototype plan.

S5. Teach UI architecture with one feature's history

Prepare a 20-minute talk for new engineers using the cart feature's history: version 1 (DOM as state, jQuery), version 2 (one big component), version 3 (feature module with a store, public API, design-system components). Show what broke at each stage and the principle that fixed it, and end with six rules.