The Web FrontendVol. 2 · Part II
0 / 0

Shelves / The Web Frontend

FE·21

UI Architecture

Organising frontend code so it can grow: component boundaries, composition, primitives, compound and headless components, design systems and tokens, feature modules and domain boundaries, shared libraries, and the coupling and abstraction trade-offs behind each.

34 topics · ~30 min read · 25-question quiz
Updated Suggest a correction

Start here: organising a user interface

The problem with the shopping list

Chapter 17's shopping list worked, but look at how it counted the remaining items: by querying the DOM for li:not(.done). The page was the data. Every feature you add (filtering, sorting, saving, an "undo") has to read the current state back out of the DOM and then update exactly the right elements by hand. Miss one update and the screen disagrees with itself: the counter says 2 while three items show as not done. In a real app with hundreds of interacting pieces, this is the main source of bugs, and it's the problem UI architecture exists to solve.

The big idea: the UI is a function of the state

Turn it around: keep the state (the data) in plain JavaScript, and write a function that produces the screen from that state. When the state changes, call it again:

JavaScript
const state = {
  items: [{ id: 1, text: "Rice (5 kg)", done: true }, { id: 2, text: "Toor dal", done: false }],
  filter: "all",
};

function render() {
  const visible = state.items.filter(i => state.filter === "all" || !i.done);
  list.replaceChildren(...visible.map(Item));
  const left = state.items.filter(i => !i.done).length;
  count.textContent = `${left} item${left === 1 ? "" : "s"} left`;
}

function toggle(id) {
  const item = state.items.find(i => i.id === id);
  item.done = !item.done;
  render();                    // never patch the DOM by hand: change the state, re-render
}

Written as a formula: UI = f(state). The count can no longer disagree with the list, because both are computed from the same data every time. Saving is JSON.stringify(state); undo is keeping old states; testing is calling render with a given state and checking the output. Every modern UI framework is built on this idea; they differ in how they make re-rendering cheap and keep things like focus and typed text intact (the full-depth section compares the three approaches, and the lab measures them).

Components: small functions that each draw one thing

Item above is a component: a function that takes some data and returns a piece of UI:

JavaScript
function Item(item) {
  const li = document.createElement("li");
  li.className = item.done ? "done" : "";
  li.append(Text(item.text), Button({ label: item.done ? "Undo" : "Done", onClick: () => toggle(item.id) }));
  return li;
}

function Button({ label, onClick, variant = "secondary" }) {
  const b = document.createElement("button");
  b.type = "button"; b.className = `btn btn-${variant}`; b.textContent = label;
  b.addEventListener("click", onClick);
  return b;
}

With three items, driven in Chromium (click the second item's button, then switch the filter, then save):

Text
initial:           [x] Rice (5 kg), [ ] Toor dal, [ ] Jaggery | 2 items left
toggle Toor dal:   [x] Rice (5 kg), [x] Toor dal, [ ] Jaggery | 1 item left
filter = active:   [ ] Jaggery | 1 item left
saved state:       [[1,true],[2,true],[3,false]]

The filter took one line of state and no DOM code at all, and the counter stayed correct through every change.

Like LEGO bricks, small components combine into bigger ones (composition): a Button inside an Item inside a List inside a ShoppingPage. The data a component receives is called its props (properties); the function it receives (onClick) lets it report events back up to whoever owns the state. That pattern, data flows down, events flow up, keeps it clear who is allowed to change what.

Good component boundaries

Where should one component end and the next begin? Rules of thumb that hold in every framework:

  • One reason to change. A PriceTag shouldn't also fetch prices. If you'd describe it with "and", it's probably two components.
  • Draw boxes around the design. Things that look like repeated boxes in a mock-up (cards, rows, chips) are usually components.
  • Keep state as low as possible, but no lower. A dropdown's open/closed flag belongs to the dropdown; the cart contents belong to something both the cart icon and the checkout page can reach.
  • Props are the contract. A component should work given only its props, so it can be reused and tested in isolation.

Primitives, patterns and design systems

As an app grows, the same building blocks appear everywhere: buttons, inputs, dialogs, tabs. Teams pull them into a design system: a shared library of primitives (Button, Input, Stack, Text), the design tokens they're styled with, and guidelines for using them. Tokens are named design decisions, usually CSS custom properties (chapter 14):

CSS
:root {
  --color-brand: #8a4b08;
  --color-text: #1f1f1f;
  --space-2: 0.5rem;
  --space-4: 1rem;
  --radius-md: 0.5rem;
  --font-body: system-ui, sans-serif;
}
.btn { padding: var(--space-2) var(--space-4); border-radius: var(--radius-md); font-family: var(--font-body); }
.btn-primary { background: var(--color-brand); color: white; }

Change --color-brand once and every primary button, link and heading follows; add a dark theme by redefining the tokens under [data-theme="dark"]. A design system makes a 50-screen app look like one product, and makes accessibility fixes (chapter 20) land everywhere at once.

Organising the code: by feature, not by type

A small app can put all its components in one folder. A large one is easier to work on when code is grouped by feature (what the user does) rather than by kind of file:

Text
src/
  app/                 the shell: routing, layout, providers. May import anything below.
  features/
    menu/              everything about browsing the menu: components, state, API calls, tests
      index.js         the feature's public surface: other code imports only this
    cart/
    checkout/
  shared/
    ui/                design-system primitives: Button, Dialog, Input
    lib/               pure helpers: money formatting, dates

The rule that keeps this healthy is dependency direction: app may use features, features may use shared, never the other way around, and one feature may use another only through its index.js. Then you can change the inside of cart without breaking checkout, and shared code never drags a whole feature along with it. The lab runs a 20-line script that enforces these rules on a sample project.

How deep to go in UI architecture

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain components, props, state, composition and design tokens
L2 Split a screen into components, lift state appropriately, use a design system
L3 Explain reconciliation strategies (re-render, virtual DOM, signals, compilers), compound and headless components, Web Components and dependency rules
L4 Diagnose state that lives in the wrong place, prop drilling, coupling between features and over-rendering
L5 Design component APIs, a design system and module boundaries for a product
L6 Govern UI architecture across teams: versioned design systems, enforced boundaries, migrations between frameworks

Components

What a component is

A component is a reusable unit of UI that bundles structure (markup), presentation (styles), behaviour (event handling, state) and an API (props, inputs, events, slots). Every modern framework (React, Angular, Vue, Svelte, Solid) and the native Web Components standard are built around components. The core idea comes from Vol. 1 ch. 2: abstraction behind an interface. A good component hides how it works and exposes a small, stable contract.

A useful model: UI = f(state). A component is a function from inputs (props plus its own state plus context) to a description of the UI. That functional core is why components compose, test and reason well (chapter 22).

Component boundaries

Where should one component end and the next begin? Good boundaries come from cohesion (things that change together stay together) and single responsibility: a component should have one reason to change. Heuristics:

  • Split when a piece has its own state or behaviour (a dropdown inside a form), is reused (the same card in three places), is complex enough to test separately, or needs different update frequencies (a live clock inside a static header, which avoids re-rendering the header).
  • Don't split purely by size. Ten tiny components that pass twenty props between them are harder to follow than one cohesive 150-line component.
  • Separate data from presentation where it pays off: a container fetches and orchestrates, and a presentational component renders props. In modern React, data hooks and server components (chapter 24) play the container role, so this matters less as a strict pattern than as a principle: keep rendering components pure and data concerns at the edges.
  • Define the API from the consumer's point of view. Write the usage first (<OrderList orders={…} onCancel={…} />), then build to it.

Signs of a bad boundary: prop drilling through many levels, a component with ten boolean props (isCompact, isSecondary, hideIcon, showBadge…) that multiply into untestable combinations, and parents reaching into children's internals.

Composition

Composition builds complex UIs by combining components rather than configuring one giant component. It's the UI version of "composition over inheritance" (Vol. 1 ch. 2). Instead of adding props for every variation, let the consumer pass content:

// ❌ Configuration explosion
<Card title="Order #42" subtitle="3 items" showIcon icon="box" footerButtonText="Track"
      onFooterButtonClick={track} variant="outlined" headerAlign="left" />

// ✅ Composition via children / slots
<Card variant="outlined">
  <Card.Header>
    <BoxIcon aria-hidden />
    <h3>Order #42</h3>
    <p>3 items</p>
  </Card.Header>
  <Card.Body>{/* anything */}</Card.Body>
  <Card.Footer><Button onClick={track}>Track</Button></Card.Footer>
</Card>

Other composition techniques: render props and function-as-children (a component calls a function you provide to render part of its output), higher-order components (wrap a component to add behaviour; this is mostly replaced by hooks in React), hooks and composables (share stateful logic without sharing UI), and Angular directives (attach behaviour to any element, such as cdkDrag or [appTooltip]).

Primitives

Primitives are the lowest-level building blocks of your UI. They have no business knowledge, are highly reusable, and are accessible:

  • Layout primitives: Stack, Inline/Cluster, Grid, Box, Container, Spacer. They encode spacing and layout rules from design tokens, so feature code rarely writes raw CSS layout.
  • Typography primitives: Text, Heading (with the semantic level separate from the visual size: <Heading level={2} size="lg">), Link.
  • Control primitives: Button, IconButton, TextField, Checkbox, Select, Dialog, Popover, Tooltip, Tabs.

A small, solid set of primitives is the foundation of a design system, and it's where accessibility, focus styles, theming and responsiveness get solved once.

Compound components

Compound components are a set of components that work together and share implicit state through context, giving consumers flexible composition with no prop plumbing. Native HTML has them: <select> with <option>, and <details> with <summary>.

TSX
const TabsContext = createContext<{ selected: string; select: (id: string) => void } | null>(null);

function Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {
  const [selected, select] = useState(defaultValue);
  return <TabsContext.Provider value={{ selected, select }}>{children}</TabsContext.Provider>;
}
function Tab({ id, children }: { id: string; children: ReactNode }) {
  const ctx = useContext(TabsContext)!;
  return (
    <button role="tab" aria-selected={ctx.selected === id} tabIndex={ctx.selected === id ? 0 : -1}
            onClick={() => ctx.select(id)}>{children}</button>
  );
}
function TabPanel({ id, children }: { id: string; children: ReactNode }) {
  const ctx = useContext(TabsContext)!;
  return ctx.selected === id ? <div role="tabpanel">{children}</div> : null;
}
Tabs.List = ({ children }: { children: ReactNode }) => <div role="tablist">{children}</div>;
Tabs.Tab = Tab; Tabs.Panel = TabPanel;

// Consumers arrange the parts however they like:
<Tabs defaultValue="profile">
  <Tabs.List><Tabs.Tab id="profile">Profile</Tabs.Tab><Tabs.Tab id="security">Security</Tabs.Tab></Tabs.List>
  <Tabs.Panel id="profile">…</Tabs.Panel>
  <Tabs.Panel id="security">…</Tabs.Panel>
</Tabs>

(A production version also needs the roving-tabindex keyboard handling and ID wiring from chapter 20, which is exactly why headless libraries exist.)

Headless components

A headless component provides behaviour, state and accessibility, without any styling or markup opinions. You supply the look. It separates the hard, generic part (keyboard navigation, focus management, ARIA wiring, positioning, typeahead) from the brand-specific part (visual design).

Library Framework Provides
React Aria (Adobe) React Hooks and components for nearly every APG pattern, with internationalisation
Radix Primitives / Base UI React Unstyled accessible components (the basis of shadcn/ui)
Headless UI React, Vue Menus, listboxes, dialogs, tabs
Ark UI / Zag.js React, Vue, Solid, Svelte Framework-agnostic state machines for widgets
Angular CDK Angular A11y (FocusTrap, LiveAnnouncer, ListKeyManager), overlay, drag-drop, virtual scroll
TanStack Table / Virtual / Form Agnostic Headless logic for tables, virtualisation, forms
Floating UI Agnostic Positioning engine for popovers and tooltips

shadcn/ui popularised a hybrid: it copies Radix-based, Tailwind-styled component source code into your repository, so you own and modify it, instead of installing a styled library as a dependency. The trade-off is that you get full control but have to merge upstream updates yourself.

The rule of thumb: don't hand-build complex interactive widgets (comboboxes, date pickers, menus, dialogs). Wrap a headless library in your design system's styling.

Design systems

What a design system contains

A design system is the single source of truth for how a product looks and behaves. It's both a design artefact and a code library:

  1. Foundations / tokens: colour, typography, spacing, radius, elevation, motion, breakpoints.
  2. Components: primitives and patterns, with documented usage, states and accessibility.
  3. Patterns and guidelines: forms, empty states, error handling, data tables, page layouts, content and voice.
  4. Tooling: a Figma library synced with code tokens, Storybook (a component workshop: isolated development, documentation, visual and interaction tests), linting, and codemods for migrations.
  5. Governance: who can change what, a contribution process, versioning and deprecation policy, and adoption metrics.

Public examples worth studying: Material Design 3, Apple's Human Interface Guidelines, GOV.UK Design System (excellent on accessibility and plain language), IBM Carbon, Shopify Polaris, Atlassian, GitHub Primer, and Adobe Spectrum (which React Aria implements).

Design tokens

Design tokens are named design decisions stored as data, so they can be shared across platforms and tools: web CSS, iOS, Android, Figma. They're usually organised in tiers:

Text
Primitive (global) tokens     → raw values:  color.teal.600 = oklch(52% 0.12 190); space.4 = 1rem
Semantic (alias) tokens       → intent:      color.action.primary = {color.teal.600}; color.text.muted
Component tokens (optional)   → specific:    button.primary.bg = {color.action.primary}

Code references semantic tokens (--color-action-primary), never primitives. Then theming (dark mode, brands, high contrast) just remaps the semantic layer:

CSS
:root {
  --color-bg: oklch(99% 0.004 190);
  --color-text: oklch(22% 0.02 190);
  --color-action-primary: oklch(52% 0.12 190);
  --space-2: 0.5rem; --space-4: 1rem;
  --radius-md: 8px;
  --font-body: "Inter", system-ui, sans-serif;
}
[data-theme="dark"] {
  --color-bg: oklch(18% 0.01 190);
  --color-text: oklch(93% 0.01 190);
  --color-action-primary: oklch(72% 0.12 190);     /* lighter in dark mode to keep contrast */
}
.btn-primary { background: var(--color-action-primary); padding: var(--space-2) var(--space-4); border-radius: var(--radius-md); }

Tokens are stored in a platform-neutral format, the W3C Design Tokens Community Group format (.tokens.json, whose first stable version arrived in 2025), and transformed with Style Dictionary (or Tokens Studio for Figma) into CSS custom properties, TypeScript constants, Tailwind theme config, Swift and Kotlin. Tailwind v4's @theme block defines tokens as CSS variables directly.

Styling approaches

Approach How Strengths Weaknesses
Global CSS + methodology (BEM) .card__title--large naming conventions No tooling; plain CSS Discipline-dependent; global namespace
CSS Modules import s from "./Card.module.css" → locally scoped class names Real scoping, plain CSS, zero runtime Separate files; dynamic styles via variables or classes
Utility-first (Tailwind) class="flex gap-2 p-4 rounded-md" Fast, consistent with tokens, tiny CSS output, no naming Verbose markup; needs component abstraction to avoid repetition
CSS-in-JS, runtime (styled-components, Emotion) Styles in JS, injected at run time Dynamic, co-located Runtime cost, problems with Server Components and streaming SSR: declining
CSS-in-JS, zero-runtime (vanilla-extract, Panda CSS, StyleX, Linaria) Written in TS, extracted to static CSS at build time Type-safe tokens, no runtime Build tooling
Scoped styles in frameworks Angular's emulated encapsulation, Vue <style scoped>, Svelte Built in Framework-specific
Shadow DOM Native encapsulation in Web Components True isolation Theming through custom properties and ::part only

The trend for 2024–2026: zero-runtime approaches (Tailwind, CSS Modules, static extraction) plus native CSS features (layers, nesting, @scope, custom properties), driven by Server Components and performance needs.

Feature modules

As an app grows, organise code by feature (domain) rather than by technical type:

Text
❌ by type (scales badly: every feature touches every folder)
src/
  components/   (200 files)
  hooks/
  services/
  utils/
  types/

✅ by feature (co-location: what changes together lives together)
src/
  app/                 ← routing, shell, providers, global layout
  features/
    checkout/
      components/  hooks/  api/  model/  checkout.routes.ts  index.ts   ← public API of the feature
    orders/
    auth/
  shared/              ← design-system wrappers, generic utils, API client: NO feature imports
  entities/            ← (optional) cross-feature domain models: User, Product

Feature-Sliced Design formalises this with layers (app → pages → widgets → features → entities → shared) and a rule that a layer may only import from layers below it. Angular apps naturally organise around lazy-loaded feature routes. Each feature exposes a small public API (index.ts) and keeps its internals private. That's the frontend version of a Java package or module boundary (Vol. 3) and of Rust's pub(crate) (Vol. 1 ch. 2).

Domain boundaries

Domain boundaries are the frontend application of Domain-Driven Design's bounded contexts (Part XIII). Checkout, Catalogue, Account and Admin have different language, data, teams and release rhythms. Align frontend modules with them:

  • Each domain owns its routes, components, state and API client.
  • Cross-domain communication goes through explicit contracts: the URL (navigate to /orders/42), events (cart:item-added), or a small shared interface. It never goes through reaching into another domain's store or components.
  • Shared concepts (User, Money) live in a deliberately small entities or shared layer.

At the extreme, domains become separately deployed micro-frontends (Module Federation, Native Federation, Single-SPA, or iframes). They give team autonomy and independent deploys, at a real cost in duplicated dependencies, inconsistent UX, runtime integration complexity and performance. Use them for organisational scaling problems (many teams, independent release cycles), not technical ones. A well-structured monorepo (chapter 30) with enforced module boundaries is usually the better first step.

Shared libraries

Code that several apps or features use (a design system, an API client, auth helpers, utilities) belongs in shared libraries. In a monorepo they're workspace packages (packages/ui, packages/api-client). Across repositories, they're published npm packages with semantic versioning. Guidelines:

  • Be strict about what goes in. "Shared" becomes a dumping ground. Code earns a place there after two or three real uses (the rule of three), not speculatively.
  • No upward dependencies: shared code never imports feature code.
  • Stable APIs, semantic versioning, changelogs (Changesets), and codemods for breaking changes.
  • Peer dependencies for frameworks (React and Angular as peers, not bundled), so consumers don't end up with two copies.
  • Ship tree-shakable ESM with exports maps and sideEffects: false (chapter 30).

Design trade-offs

Reuse

Reuse is valuable when the reused thing is stable and genuinely the same concept: a design-system Button, a date-formatting function, an HTTP client. Reuse is harmful when two things merely look similar today but change for different reasons. A shared <UserCard> used by Admin (which needs edit controls), the public profile (which needs privacy rules) and checkout (which needs a compact layout) accumulates flags until nobody can change it safely. Here duplication is cheaper than the wrong abstraction.

The DRY principle ("Don't Repeat Yourself") is about knowledge, not text. Two identical-looking snippets that encode different business rules aren't duplication.

Coupling and dependency direction

Coupling is how much one module must know about another to work. Tightly coupled code changes together and breaks together. Frontend forms of coupling include components that read global stores directly, components that depend on a specific API response shape, CSS that depends on DOM structure (.sidebar > div > ul li a), and features importing each other's internals.

Dependency direction is the most important architectural rule: dependencies should point toward stability and abstraction. In a frontend:

Text
features ──▶ entities ──▶ shared ──▶ (platform: React/Angular, browser APIs)
   │                         ▲
   └──── design system ──────┘
UI components ──▶ hooks/services (interfaces) ◀── API adapters (implementations)
  • Stable, generic code (the design system, utilities) must not depend on volatile, specific code (features).
  • Dependency inversion (the D in SOLID; Vol. 3): components depend on an interface such as useOrders() or an Angular OrderService token, not on fetch('/api/v2/orders') directly. The implementation can then change (REST → GraphQL, a mock in tests, a cache layer) without touching the UI. Angular's DI does this explicitly (chapter 23). In React, hooks and context are the mechanism.
  • Enforce boundaries with tooling, because conventions erode: ESLint import/no-restricted-paths or eslint-plugin-boundaries, Nx enforce-module-boundaries tags, dependency-cruiser, and TypeScript project references.

Abstraction cost

Every abstraction has a cost: indirection (more files and jumps to understand one behaviour), learning (new team members must learn your abstractions on top of the framework's), rigidity (it encodes assumptions that become wrong), and leaks (eventually someone needs what the abstraction hides). A wrapper around a component library that re-exposes 90% of its props adds cost for little value. A design-system Button that enforces tokens, focus styles and loading states adds real value.

Ask before abstracting: What does this hide that callers shouldn't care about? What will it make harder?

Premature abstraction

Premature abstraction means generalising before you understand the variations. It's the frontend twin of premature optimisation. Typical symptoms:

  • A generic <DataView> or <FormBuilder> driven by giant configuration objects, created after seeing one table or one form.
  • Props named after hypothetical future needs.
  • "Framework within a framework" internal layers that nobody else understands.

Guidance from experienced teams:

  • The rule of three: tolerate duplication until the third occurrence. By then you can see which parts actually vary.
  • "Duplication is far cheaper than the wrong abstraction" (Sandi Metz). When an abstraction keeps needing conditionals for each caller, inline it back into the callers and re-extract what is genuinely shared.
  • AHA programming: "Avoid Hasty Abstractions" (Kent C. Dodds). Optimise for change first, then abstract.
  • Prefer composition (small pieces combined by consumers) to configuration (one piece with many switches), because composition defers decisions to the people who have the context.

How frameworks keep the screen in sync

Three strategies for UI = f(state)

Re-running render() and rebuilding the whole DOM is correct but has two costs: it's wasteful for large UIs, and it destroys whatever the browser was holding in the old elements: keyboard focus, text being typed, scroll positions, running CSS transitions, selection. Frameworks keep the programming model (describe the UI from state) while changing only what actually differs. There are three main strategies, and every framework you'll meet uses one or a mix:

Strategy How an update works Work per update grows with… Used by
Virtual DOM diffing re-run the component functions to produce a lightweight description of the UI (plain objects); compare it with the previous description; apply only the differences to the real DOM the size of the re-rendered component subtree React, Preact, Vue (with compiler hints), Inferno
Fine-grained reactivity (signals) each piece of state is a reactive value; each DOM binding subscribes to exactly the values it reads; changing a value re-runs only its subscribers the number of bindings that read the changed value SolidJS, Angular signals, Vue refs, Preact signals, Svelte 5 runes, Qwik
Compile-time analysis a compiler reads the templates and generates code that updates exactly the right DOM nodes for each change the bindings affected (like signals), decided ahead of time Svelte, Angular's template compiler, React Compiler (for memoisation), Marko

The lab builds a tiny version of each against the same 1,000-item list. Changing one item's done flag:

Text
strategy          DOM nodes touched   per update    focus and typed text in a search box
innerHTML          2,004              0.71 ms       lost
virtual DOM diff       1              0.44 ms       kept      (1,000 comparisons to find it)
signals                1              0.010 ms      kept      (1 effect ran)

All three gave the right screen; they differ in how much work it took to find the one change. Virtual DOM is simple and flexible (components are just functions) but does work proportional to what re-rendered, which is why React offers memoisation and why the React Compiler adds it automatically. Signals do work proportional to what changed, at the price of a reactive programming model with its own pitfalls (reading a value outside a tracking context, accidental dependencies). Both preserve focus and input because they update existing elements instead of replacing them, which is also why lists need stable keys: without a key, a diff can't tell "item 5 moved" from "item 5 changed into item 6", and reused elements end up with the wrong state.

Keys and identity

When a list re-renders, the framework must match new items to existing DOM nodes. Matching by position breaks as soon as items are inserted, removed or reordered: delete the first row of a list of text inputs, and every row's typed text appears to shift up by one, because the framework reused row 1's input for what is now a different item. Matching by a stable key (a database id, never the array index for dynamic lists) lets it move the right nodes. React's key, Vue's :key, Angular's @for (…; track item.id), Svelte's {#each items as item (item.id)} and Solid's <For> (keyed by reference) all solve the same problem.

Web Components: the platform's own component model

Custom elements and shadow DOM

The browser has a built-in component system that works in any framework or none. Custom elements let you define new HTML tags with a class; shadow DOM gives each one a private subtree whose styles don't leak in or out; <template> and slots let users pass content in.

JavaScript
class RatingStars extends HTMLElement {
  static observedAttributes = ["value", "max"];
  #root = this.attachShadow({ mode: "open" });
  connectedCallback() { this.render(); }
  attributeChangedCallback() { this.render(); }
  render() {
    const value = Number(this.getAttribute("value") ?? 0), max = Number(this.getAttribute("max") ?? 5);
    this.#root.innerHTML = `
      <style>button { background: none; border: 0; font-size: 1.5rem; color: var(--star-colour, gold); }</style>
      <span part="label">Rating:</span>
      ${Array.from({ length: max }, (_, i) =>
        `<button aria-label="${i + 1} of ${max}" aria-pressed="${i < value}">${i < value ? "★" : "☆"}</button>`).join("")}`;
    this.#root.querySelectorAll("button").forEach((btn, i) => btn.onclick = () => {
      this.setAttribute("value", i + 1);
      this.dispatchEvent(new CustomEvent("rate", { detail: i + 1, bubbles: true, composed: true }));
    });
  }
}
customElements.define("rating-stars", RatingStars);
HTML
<style>
  button { background: red; color: white; }            /* the page's own button style */
  rating-stars { --star-colour: #8a4b08; }               /* custom properties cross the shadow boundary */
  rating-stars::part(label) { font-style: italic; }      /* so do explicitly exported parts */
</style>
<rating-stars value="3" max="5"></rating-stars>

Measured in Chromium:

Text
page button background: rgb(255, 0, 0)       star button background: rgba(0, 0, 0, 0)   (page CSS didn't leak in)
star colour: rgb(138, 75, 8)                  label: italic                              (tokens and parts did)
document.querySelectorAll("button").length: 1 (the stars are invisible to page queries)
stars rendered: ★★★☆☆
after clicking "5 of 5": value 5, rate event detail 5, event target seen by the page: RATING-STARS

Encapsulation worked both ways: the page's red button rule didn't reach the stars, and page-level querySelectorAll couldn't see inside. The component exposed exactly two styling hooks (a custom property and a part), and its event was retargeted: the page saw it come from <rating-stars>, not from an internal button (composed: true lets it cross the shadow boundary at all). Web Components suit design systems shared across teams using different frameworks, embeddable widgets, and long-lived leaf components; Lit is the common thin library on top of them. Their trade-offs: server-side rendering needs Declarative Shadow DOM (<template shadowrootmode="open">), form participation needs ElementInternals, and accessibility relationships (aria-labelledby) can't yet point across shadow boundaries without the newer reference-target proposals.

Lab: architecture you can measure

Three experiments in Chromium 153 and Node 22: the cost of the three update strategies, the bug that keys prevent, and an automated check for dependency direction.

Experiment 1: three ways to apply UI = f(state)

A 1,000-item list with a search box above it. The user has typed "dos" in the search box (it has focus) when item 500 is marked done. Each strategy re-applies the state; a MutationObserver counted DOM nodes inserted, removed or changed, and each update was timed over 20 runs:

JavaScript
// 1. rebuild: replace everything
app.innerHTML = "<input id=search><ul>" + items.map(i => `<li class="${i.done ? "done" : ""}">${i.text}</li>`).join("") + "</ul>";

// 2. keyed virtual-DOM diff: describe the UI as objects, compare with last time, patch differences
const view = () => items.map(i => ({ key: i.id, cls: i.done ? "done" : "", text: i.text }));
patch(view());       // walks all 1,000 descriptions, changes el.className on the one that differs

// 3. signals: each <li> subscribed to its own reactive value when it was created
done[500].set(true); // runs exactly the one subscriber that sets that li's className
Text
innerHTML  {"nodesTouched":2004,"msPerUpdate":"0.71","focusKept":false,"typedTextKept":""}
vdomDiff   {"nodesTouched":1,"comparisons":1000,"msPerUpdate":"0.44","focusKept":true,"typedTextKept":"dos"}
signals    {"nodesTouched":1,"msPerUpdate":"0.010","effectsRun":1,"focusKept":true,"typedTextKept":"dos"}
  • Rebuilding replaced 2,004 nodes (1,002 out, 1,002 in) and threw away the user's focus and typed text: the search box they were typing in was destroyed and recreated empty. That alone rules it out for interactive UIs, before any performance argument.
  • Diffing touched one node and kept focus, but compared 1,000 descriptions to find it. That's still fast here (0.44 ms); it becomes a problem when components re-render large subtrees on every keystroke, which is what React's memoisation (memo, useMemo, and the React Compiler, chapter 22) is for.
  • Signals touched one node after running one effect, 44× less time than the diff. The cost moved elsewhere: creating 1,000 subscriptions up front, and a programming model where dependencies are tracked automatically (chapter 23's Angular signals).

These numbers are for a mini-framework of 20 lines each; real frameworks add batching, scheduling and dev-mode checks, but the shape (rebuild ≫ diff > fine-grained) is the same one in public benchmarks such as js-framework-benchmark.

Experiment 2: why lists need stable keys

Three dishes, each row with a text input where the user typed a note. The user removes the first dish. A tiny keyed renderer reuses existing <li> elements by key and only updates their text:

JavaScript
items.forEach((it, i) => {
  const key = keyBy === "index" ? i : it.id;
  let li = prev.get(key) ?? createRow();
  li.querySelector("span").textContent = it.name;     // update the label; the input keeps its typed value
  …
});
Text
before:               Dosa: "extra chutney", Idli: "no onion", Vada: "crispy"
keyed by array index: Idli: "extra chutney", Vada: "no onion"
keyed by item id:     Idli: "no onion", Vada: "crispy"

Keyed by position, the renderer reused row 0's element for Idli and row 1's for Vada, relabelling them, so the notes stayed where they were and now belong to the wrong dishes. The kitchen gets "Idli, extra chutney" and Vada's "crispy" is gone. Keyed by id, Dosa's row was removed and the others kept their own inputs. This is exactly the bug React warns about with "Each child in a list should have a unique key", and why index keys are only safe for lists that never reorder, insert or delete.

Experiment 3: enforcing dependency direction

A sample project laid out as in Start here (app → features → shared), with four mistakes planted. A 20-line Node script reads every import and checks two rules: no upward dependencies, and features may only use other features through their public index.js:

JavaScript
if (rank[layer(target)] > rank[layer(file)]) problem("upward dependency");
if (bothAreFeatures && differentFeature && targetPath !== "index.js") problem("reaches into internals");
if (bothAreFeatures && differentFeature) problem("feature → feature");
Text
features/cart/index.js       imports features/menu/index.js            ✗ feature → feature (cart → menu)
features/checkout/index.js   imports features/cart/index.js            ✗ feature → feature (checkout → cart)
features/checkout/index.js   imports features/cart/internal/coupons.js ✗ reaches into cart's internals
shared/lib/analytics.js      imports features/checkout/index.js        ✗ upward dependency: shared → features

Not every finding is equally bad. checkout → cart through cart's public index may be an acceptable, intended dependency (many teams allow feature-to-feature imports through public APIs, or define an explicit allow-list); reaching into cart/internal and shared → features are the ones that turn a codebase into a tangle, because they couple code to implementation details and create cycles. In real projects use a maintained tool: eslint-plugin-boundaries or import/no-restricted-paths, Nx's module boundary rules, dependency-cruiser, or Angular's and Java's equivalents (ArchUnit in the Java world). Run it in CI so the architecture is enforced, not just documented.

Try it yourself

  1. Add a "move item to top" action to experiment 2. Which keying strategy keeps the notes correct?
  2. Extend experiment 1's signal version with a derived value (a "computed" count of done items) that updates only when a done signal changes.
  3. Rewrite the shopping list as a <shopping-list> custom element with a shadow root and a change event, then use it in a plain page and inside a React or Angular app.
  4. Run dependency-cruiser on a real codebase you work on and draw its top-level dependency graph. Are there cycles?

Revision sheet: UI architecture

Key ideas

  • UI = f(state): keep state in data structures and derive the screen; never use the DOM as the source of truth.
  • Components take props and render UI; data flows down, events flow up through callbacks; state lives at the lowest common owner.
  • Boundaries: one reason to change; props as the contract; containers (data) vs presentational (display) where it helps.
  • Patterns: composition over configuration; slots/children; compound components sharing implicit state (<Tabs><Tabs.List/><Tabs.Panel/></Tabs>); headless components that provide behaviour and accessibility without styles (Radix, React Aria, Headless UI, Angular CDK).
  • Design systems: tokens (colour, space, type, radius, motion) → primitives → patterns → guidelines; versioned and documented (Storybook); accessibility built in.
  • Sync strategies: rebuild (loses state), virtual DOM diff (work ∝ re-rendered subtree), signals (work ∝ changed bindings), compilers (decided at build time); stable keys for lists.
  • Web Components: custom elements, shadow DOM (style and query encapsulation, event retargeting), slots, parts, custom properties; Declarative Shadow DOM for SSR; ElementInternals for forms.
  • Code organisation: by feature; public index per feature; dependency direction app → features → shared; enforce with lint rules.
  • Trade-offs: reuse vs coupling; the cost of abstraction; the rule of three before extracting; prefer duplication over the wrong abstraction.

Numbers to remember

  • Lab: one change in a 1,000-item list touched 2,004 nodes by rebuilding, 1 by diffing (1,000 comparisons) or by signals (1 effect).
  • Rule of three: extract a shared abstraction on the third real use, not the first.

Pitfalls

  • Duplicated state (the same fact stored twice and drifting); derived data stored instead of computed.
  • Prop drilling through many layers instead of composition or context.
  • Index keys in dynamic lists.
  • "God" components and "util" dumping grounds; shared code importing features.
  • Premature abstraction: configurable components with dozens of boolean props.
  • Design-system forks: copying components instead of contributing changes back.

Glossary

  • Props: inputs a component receives from its parent.
  • Lifting state: moving state up to the nearest common ancestor of the components that need it.
  • Reconciliation: matching a new UI description to existing DOM nodes and applying differences.
  • Signal: a reactive value whose readers are tracked and re-run when it changes.
  • Headless component: behaviour and accessibility without markup or styles opinions.
  • Shadow root: the private DOM subtree attached to a custom element.