SD·195B
Frontend Depth II: React, Performance, Security, Testing, Architecture, Deployment
The rest of the frontend track at L5/L6, with experiments in React 19 and Chromium: ladders; React at L5 — counting renders (3,500 row renders for seven keystrokes, and why React.memo alone didn't help until the callback was stable), state categories, effects, server components and the compiler; web performance as a production discipline — a render-blocking script pushing LCP from 40 ms to 860 ms, budgets, real-user monitoring, and the levers that matter; web security — a DOM XSS that executes through innerHTML, is neutralised by textContent and blocked by a nonce-based CSP, plus token storage, CSRF, clickjacking and the npm supply chain; testing strategy (what each layer proves, Playwright and Testing Library, flake); frontend architecture choices (SPA, SSR, SSG, islands, server components, micro-frontends) with their costs; and deployment (atomic, versioned assets, version skew, previews, RUM-driven rollbacks).
Start here: what L5/L6 frontend engineering looks like
Frontend depth II is about the decisions that shape a whole product's front end: how React renders and when it shouldn't, how to keep pages fast as they grow, how to protect users from XSS and supply-chain attacks, how to test at the right levels, how to structure a large codebase, and how to deploy safely. At L5 you set these choices and budgets; at L6 you keep them working across teams and years.
One example: two attributes worth 800 ms and a layout jump
The lab served the same small page four ways, with a script that took 0.8 s to download and a 600 × 300 image that took 0.5 s:
| Page | First Contentful Paint | Cumulative Layout Shift |
|---|---|---|
script in <head> (render-blocking) |
~835 ms | 0 |
same script with defer |
~28 ms | 0 |
image without width/height |
20–24 ms | 0.097 |
image with width/height |
20 ms | 0 |
One defer attribute let the browser paint the menu 30× sooner; two size attributes stopped the text from jumping down when the image arrived (0.097 is close to the 0.1 "needs improvement" line from a single image). Core Web Vitals (LCP, INP, CLS) put numbers on what users feel; an L5 engineer turns them into budgets enforced in CI and watched in real-user monitoring.
How deep to go in frontend engineering
Volume 17 defines six mastery levels; for this chapter's topics they look like this:
| Level | You can… |
|---|---|
| L1 | name React's rendering model, Core Web Vitals, frontend threats and test levels |
| L2 | build React apps with tests, sensible performance and secure defaults |
| L3 | explain rendering strategies, loading and rendering costs, browser security mechanisms |
| L4 | diagnose slow renders, poor vitals, XSS risks, flaky tests and bundle bloat |
| L5 | set architecture, budgets, testing strategy and security policies for a product |
| L6 | run a large front end across teams: platforms, design systems, deployment and RUM |
The ladders
| Level | React | Web performance | Web security | Testing | Architecture & deployment |
|---|---|---|---|---|---|
| L1 | Knows components, props, state | Knows that speed matters; knows Lighthouse | Knows XSS and CSRF names | Knows unit vs E2E | Knows SPA vs server rendering |
| L2 | Builds features with hooks, forms, data fetching, routing | Optimises images, uses lazy loading, reads Lighthouse | Uses framework escaping, HttpOnly cookies | Writes component and E2E tests | Deploys to a static host/CDN with CI |
| L3 | Explains reconciliation, render/commit phases, hooks' rules and why, batching, concurrent rendering, server components | Explains the rendering pipeline, Core Web Vitals definitions, the network waterfall, caching, JS parse/compile cost | Explains XSS variants, the same-origin policy, CORS, CSP, cookies' attributes, Trusted Types | Explains what each test type proves, test doubles, why tests flake | Explains rendering models (CSR, SSR, SSG, ISR, streaming, islands, RSC) and their trade-offs |
| L4 | Diagnoses re-render storms, stale closures, effect loops, hydration mismatches with the Profiler | Diagnoses LCP/INP/CLS regressions from field data and traces | Finds DOM XSS sinks, CSP gaps, token leakage in code review | Diagnoses and fixes flaky tests | Diagnoses version skew, cache problems, deploy-related errors |
| L5 | Designs state architecture and component APIs; picks frameworks | Sets budgets; designs the loading strategy | Designs auth token handling, CSP, dependency policy | Designs the test strategy and its CI | Chooses rendering model, monorepo/micro-frontend structure, release strategy |
| L6 | Maintains large React apps across major upgrades | Owns field performance over time | Responds to frontend security incidents; supply chain | Keeps suites fast and trusted at scale | Operates frontend releases with flags, canaries and RUM |
React at L5
Renders are the unit of cost
React re-renders a component when its state changes, when its parent re-renders (by default), or when a context it reads changes. A render is calling your function and diffing the result (194G); it's cheap individually and expensive in bulk. Counting real renders in React 19: a search box above a 500-row menu, typing seven characters:
// Counting React renders: typing in a search box re-renders a 500-row menu list unless the list is memoised
// with stable props. Runs React 19 in jsdom.
let rowRenders = 0;
const Row = ({ dish, onSkip }) => { rowRenders++; return h("li", null, dish.name, h("button", { onClick: () => onSkip(dish.id) }, "skip")); };
const MemoRow = React.memo(Row);
function App({ variant }) {
const [query, setQuery] = React.useState("");
const unstable = (id) => console.log("skip", id); // new function every render
const stable = React.useCallback((id) => console.log("skip", id), []); // same function across renders
const RowC = variant === "plain" ? Row : MemoRow;
const onSkip = variant === "memo + useCallback" ? stable : unstable;
return h("div", null, h("input", { value: query, onChange: (e) => setQuery(e.target.value) }),
h("ul", null, dishes.map((d) => h(RowC, { key: d.id, dish: d, onSkip }))));
}
plain row renders for 7 keystrokes: 3500
memo, inline callback row renders for 7 keystrokes: 3500
memo + useCallback row renders for 7 keystrokes: 0
The middle row is the L4 lesson: React.memo compares props by reference, and an inline arrow function is a new function on every render, so memo never skips. Only with a stable callback does it work. L5 is choosing among the real fixes rather than sprinkling memo:
- Move state down: if only the input needs
query, put the state in a smallSearchBoxcomponent; the list's parent never re-renders. - Lift content up / composition: pass the expensive list as
childrento the component that owns the fast-changing state; children created by the parent don't re-render when the child's state changes. - Memoise deliberately where profiling shows cost (or let the React Compiler (stable in 2025) insert memoisation automatically at build time, which makes the inline-callback trap disappear for code it can analyse).
- Defer non-urgent updates (
useDeferredValuefor filtering the list while typing stays responsive) and virtualise long lists.
State, effects and data
- Categories of state (L5): server state (data owned by the backend: fetched, cached, invalidated; use TanStack Query, SWR, RTK Query, or framework loaders rather than hand-rolled
useEffectfetching), URL state (filters, pagination: shareable and survives refresh), form state, local UI state, and global client state (small, often just session and preferences). Most "state management" problems are server state treated as client state. - Effects are for synchronising with external systems (subscriptions, timers, imperative widgets), not for deriving data (compute during render) or reacting to events (do it in the handler). Missing cleanup causes leaks and double subscriptions (Strict Mode's double invocation in development exposes them).
- Server components (React 19 with frameworks like Next.js): components that run only on the server, fetch data directly, and send rendered output (not their code) to the client, shrinking bundles; client components hydrate for interactivity. They change where the client/server boundary is, which raises new questions (what data crosses the boundary, caching, security of server actions).
Web performance as a discipline
What to measure: Core Web Vitals in the field at the 75th percentile, segmented by device class and network (Volume 16, ch. 188): LCP (loading), INP (responsiveness), CLS (visual stability). Lab tools (Lighthouse, WebPageTest) explain; field data (CrUX, your own RUM) decides.
The biggest LCP lever is usually the critical path. The same page, with an 800 ms script loaded three ways (Chromium via Playwright):
<head><script src="/app.js"></script></head> <!-- parser-blocking: HTML stops until it downloads and runs -->
<head><script defer src="/app.js"></script></head> <!-- downloads in parallel, runs after parsing -->
<head><script type="module" src="/app.js"></script></head> <!-- modules are deferred by default -->
blocking <script src> in <head> LCP ≈ 860 ms
<script defer> LCP ≈ 40 ms
<script type=module> LCP ≈ 80 ms
The page's content was there in the HTML all along; the blocking script hid it for 800 ms. Real-world equivalents: synchronous tag managers and A/B testing scripts, render-blocking web fonts, CSS imported from slow third parties, and client-side-rendered apps where the content doesn't exist until the bundle runs.
The levers, roughly in order of impact:
- Ship less JavaScript: every kilobyte costs download, parse, compile and execute time, far more on mid-range phones. Code-split by route, remove unused dependencies (bundle analysers), prefer server rendering for content.
- Fix the critical path: HTML first with content in it (SSR/SSG), preload the LCP image (
fetchpriority="high"), inline critical CSS, defer everything else, preconnect to required origins. - Images: correct sizes (
srcset/sizes), modern formats (AVIF/WebP), lazy-load below the fold (never the LCP image), explicit dimensions to prevent CLS. - Caching and the network: CDN, long-lived hashed assets, HTTP/2 or HTTP/3, compression (Brotli for text), fewer origins.
- Main-thread work for INP: break long tasks, debounce expensive handlers, give immediate visual feedback before heavy work, move work to workers, avoid layout thrashing (195A).
- Third parties: audit their cost; load them after the page is interactive or in workers (Partytown-style), or remove them.
L5/L6 practice: performance budgets in CI (bundle size per route, Lighthouse thresholds on key pages) that fail builds; RUM dashboards per release so a regression is tied to a deploy; ownership (someone is accountable for the p75 numbers); and testing on representative devices and networks (in India, a mid-range Android phone on 4G is the median user, not the developer's laptop on office Wi-Fi).
Web security for the frontend
DOM XSS, reproduced
A dish note entered by one user and shown to another (or to an admin), rendered three ways in Chromium:
const note = `Extra raita <img src=x onerror="window.pwned=(window.pwned||0)+1">`;
document.getElementById('note').innerHTML = note; // case 1 and 3
document.getElementById('note').textContent = note; // case 2
// case 3 adds: <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'nonce-abc'">
innerHTML, no CSP injected handler ran: YES rendered: Extra raita <img src="x" onerror="window
textContent, no CSP injected handler ran: no rendered: Extra raita <img src=x onerror="windo
innerHTML, CSP script-src 'nonce-…' (no unsafe-inline) injected handler ran: no rendered: Extra raita <img src="x" onerror="window
innerHTML parses the string as HTML, creating an <img> whose onerror handler runs attacker code with the victim's session (steal data, perform actions as them). textContent treats it as text. A strict CSP (only scripts carrying a per-response nonce may run; inline event handlers are blocked) stops the payload executing even though the dangerous sink was used: defence in depth. Note that the markup still got into the DOM, and HTML injection without script can still deface pages or phish.
L3 catalogue: XSS sinks (innerHTML, outerHTML, document.write, insertAdjacentHTML, eval, new Function, setTimeout(string), href="javascript:…", React's dangerouslySetInnerHTML, framework bypasses like Angular's bypassSecurityTrustHtml); sources (URL fragments and parameters, postMessage, stored data, third-party APIs). Frameworks escape text by default, so XSS in modern apps concentrates in those escape hatches and in URL attributes.
L5 decisions:
- CSP: a strict, nonce- or hash-based
script-srcwith'strict-dynamic',object-src 'none',base-uri 'none', deployed first inContent-Security-Policy-Report-Onlymode to collect violations;frame-ancestorsto prevent clickjacking. - Trusted Types (Chromium-based browsers): a CSP mode that makes dangerous sinks reject plain strings, forcing all HTML through reviewed sanitising policies (DOMPurify).
- Token storage: session or refresh tokens in HttpOnly, Secure, SameSite cookies, not
localStorage(any XSS can readlocalStorage; it can't read HttpOnly cookies, though it can still act within the page). For SPAs, the backend-for-frontend pattern keeps OAuth tokens on the server entirely. - CSRF:
SameSite=LaxorStrictcookies plus CSRF tokens orOriginchecks for state-changing requests. - CORS configured narrowly on the API (194G); never reflect arbitrary origins with credentials.
- Supply chain: npm packages run code at install and in your bundle. Lockfiles committed and
npm ciin CI, minimal dependencies, review new ones (maintainers, install scripts, size), automated update PRs with tests, Subresource Integrity (integrity=) for any script from a CDN, and alerts on known-malicious versions (2025 saw several large npm account takeovers and self-propagating worms injecting code into popular packages).
Testing strategy
What each layer proves:
| Layer | Tools | Proves | Cost / risk |
|---|---|---|---|
| Static | TypeScript, ESLint (with a11y and security plugins) | Whole classes of errors can't occur | Nearly free; runs on save |
| Unit | Vitest/Jest | Pure logic (formatters, reducers, validation) is correct | Fast; can over-specify implementation |
| Component / integration | Testing Library with Vitest/Jest, or Playwright component tests | Components behave correctly as users use them (query by role and label, not by class names) | Moderate; jsdom isn't a real browser |
| Contract | Pact, generated types | Front end and API agree | Needs provider verification in the backend's CI |
| End-to-end | Playwright, Cypress | Critical journeys work in real browsers against a deployed stack | Slow, flakier: keep to the few journeys that matter |
| Visual regression | Playwright screenshots, Chromatic | Nothing looks broken | Noise from fonts/animation; needs stable rendering |
| Accessibility | axe in component and E2E tests | Automatable WCAG checks pass | Catches only part (195A) |
| Performance | Lighthouse CI, bundle budgets | Budgets hold | Lab only; pair with RUM |
The testing trophy (Kent C. Dodds) argues for most effort in integration/component tests for UIs, because they give the most confidence per unit of cost; the backend's test pyramid (Volume 11) remains right for logic-heavy code. A component test written the Testing Library way:
// SkipButton.test.tsx — test behaviour through the accessibility tree, the way users (and assistive tech) find things
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { SkipButton } from "./SkipButton";
test("skipping asks for confirmation, then reports the credit", async () => {
const onSkip = vi.fn().mockResolvedValue({ creditBalance: 3 });
render(<SkipButton date="2026-11-06" onSkip={onSkip} />);
await userEvent.click(screen.getByRole("button", { name: /skip friday, 6 november/i }));
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
expect(onSkip).toHaveBeenCalledWith("2026-11-06");
expect(await screen.findByRole("status")).toHaveTextContent("Skipped. You now have 3 credits.");
});
Flaky tests (L4): arbitrary sleeps instead of waiting for conditions (Playwright's auto-waiting assertions and Testing Library's findBy* exist for this), shared state between tests, real time and time zones (fake timers, fixed clocks), animations, network calls to real third parties, order dependence, and test data collisions in shared environments. L6: track flake rates, quarantine with an owner and a deadline, and treat a flaky test as a bug (a suite people don't trust gets ignored).
Frontend architecture
| Rendering model | How | Good for | Costs |
|---|---|---|---|
| CSR (SPA) | Empty HTML, JS renders everything | App-like tools behind login | Slow first load, SEO depends on crawler JS, all logic in the bundle |
| SSR | Server renders HTML per request; JS hydrates | Dynamic, personalised pages needing fast first paint and SEO | Server cost and latency; hydration cost; complexity |
| SSG | HTML built at deploy time | Content that changes rarely (marketing, docs) | Rebuilds on change; not for personalised content |
| ISR / revalidation | Static pages regenerated in the background on a schedule or on demand | Large catalogues that change occasionally | Staleness windows; framework/host coupling |
| Streaming SSR | Server sends HTML in chunks as data resolves (Suspense boundaries) | Pages with slow and fast data | Complexity; error handling mid-stream |
| Islands | Mostly static HTML with isolated interactive components hydrated individually (Astro) | Content sites with some interactivity | Cross-island state is harder |
| React Server Components | Server-only components plus client components; data fetched on the server | Data-heavy React apps wanting smaller bundles | New mental model; framework-dependent; caching complexity |
L5 choices beyond rendering: framework (Next.js, Remix/React Router, Astro, Angular, Vue/Nuxt, SvelteKit: choose by team skills, rendering needs and ecosystem, not benchmark charts); state architecture (above); monorepo with shared design system and API client packages (Nx/Turborepo); micro-frontends (independently deployed parts of one UI via module federation or composition at the edge) only when organisational scale demands independent team deployment, because they cost bundle duplication, inconsistent UX, and integration testing complexity; a design system as the main lever for consistency and accessibility at scale.
Deployment
- Atomic, immutable releases: hashed asset filenames (
app.3f9a1c.js, cached for a year),index.htmlwithno-cache, so a deploy is a pointer change and rollback is instant (Volume 16). - Version skew: users keep old tabs open for days. Their old JS calls your new API (keep APIs backward compatible) and lazy-loads old chunks (keep old assets available; catch chunk-load errors and reload); some platforms offer skew protection that routes a client to the backend version it was built against.
- Preview deployments per pull request for review by design and product.
- Feature flags and gradual rollouts for front-end changes too, with RUM and error tracking (Sentry and similar) segmented by release so a regression rolls back on evidence.
- Configuration at runtime rather than baked into the bundle, so the same build runs everywhere (Volume 16, ch. 190).
- Security headers set at the CDN/edge (CSP, HSTS,
X-Content-Type-Options,Referrer-Policy,Permissions-Policy).
Lab: loading and layout stability, measured
Setup. A small Python HTTP server on the lab machine serving one menu page four ways, a script that takes 0.8 s to respond, and a real 600 × 300 PNG that takes 0.5 s; Chromium (headless, Playwright) loads each page three times in a fresh context with caching disabled. First Contentful Paint comes from performance.getEntriesByName('first-contentful-paint'); layout shift from a PerformanceObserver on layout-shift entries (excluding shifts after input). Scope: a local server has no network latency, so these isolate the effect of markup choices.
Results
| Variant | Markup | FCP (3 runs) | CLS (3 runs) |
|---|---|---|---|
| blocking | <script src="/slow.js"> in <head> |
832 / 840 / 836 ms | 0.000 |
| defer | <script src="/slow.js" defer> |
24 / 32 / 28 ms | 0.000 |
| no size | <img src="/slow.png" style="width:600px"> |
24 / 20 / 24 ms | 0.097 |
| sized | <img … width="600" height="300" style="width:600px;height:auto"> |
20 / 20 / 20 ms | 0.000 |
- The blocking script held the entire first paint for its 0.8 s download, though the page needed nothing from it to show the menu.
deferlet parsing and painting continue. On real networks, every render-blocking resource adds its full round trips to FCP and LCP; a performance budget should list them. - The unsized image reserved no space; when it arrived, the paragraphs below jumped down by 300 px (CLS 0.097, just under the 0.1 "good" limit from a single image on a short page). With
widthandheight, the browser computed the aspect ratio before loading and reserved the space, even with responsiveheight: auto. - A first version used a 1 × 1 placeholder image, which produced small shifts even when sized, because the image's real aspect ratio differed from the declared one. Declared dimensions must match the real image (or use
aspect-ratio).
Making it stick
These are one-line fixes that regress silently. L5 practice turns them into gates: Lighthouse CI or WebPageTest budgets in the pipeline (FCP, LCP, CLS, total blocking time, JavaScript bytes), lint rules for images without dimensions, and real-user monitoring at p75 by page and device class, because lab runs on a fast machine say little about a low-end phone on a 3G network.
Try it yourself
- Add
asyncinstead ofdeferand two scripts that depend on each other; what breaks? - Add a web font with
font-display: swapand measure its layout shift; then fix it withsize-adjustor a matched fallback. - Put Lighthouse CI in a pipeline with a CLS budget of 0.05 and make the unsized page fail.
- Measure the same variants with 4× CPU throttling and a "Slow 4G" network profile.
Revision sheet: frontend depth II
Key ideas
- React at L5: rendering strategies (CSR, SSR, SSG, streaming, Server Components), state placement, re-render control, data fetching and caching, concurrency features.
- Web performance as a discipline: Core Web Vitals (LCP, INP, CLS) at p75 in the field; critical path, render-blocking resources, images, fonts, JavaScript cost; budgets in CI; RUM.
- Frontend security: XSS (auto-escaping, Trusted Types, sanitisation), CSP, SRI, CSRF and cookies (SameSite), clickjacking, dependency supply chain, secrets never in bundles.
- Testing strategy: unit, component, integration, end-to-end, visual and accessibility checks; flake control; contract tests with the backend.
- Architecture: modules and boundaries, design systems, monorepos, micro-frontends (rarely), state management choices.
- Deployment: immutable assets with hashed names, CDN caching, feature flags, rollbacks, version skew between client and server.
Numbers to remember
- Lab: render-blocking script → FCP ~835 ms;
defer→ ~28 ms. - Lab: unsized 600 × 300 image → CLS 0.097; sized → 0.
- Core Web Vitals "good": LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1, at p75.
Pitfalls
- Third-party scripts in
<head>withoutdefer/async. - Images and embeds without reserved space.
- Measuring only in the lab on fast hardware.
dangerouslySetInnerHTMLwith unsanitised input; no CSP.- Client/server version skew after deploys (old bundles calling new APIs).
Glossary
- FCP / LCP: first / largest contentful paint.
- CLS: cumulative layout shift.
- RUM: real-user monitoring.
- Trusted Types: a browser API that blocks unsafe DOM sinks unless values are vetted.
- Version skew: different client and server versions running together.