JavaScript in one page
A dynamically typed, single-threaded, event-driven language whose sharp edges explain why TypeScript exists.
You cannot understand TypeScript without understanding what it is layered on top of, so this chapter is the shortest useful summary of JavaScript itself.
JavaScript is dynamically typed — a variable's type is a property of its current value, not of the variable — and weakly typed, meaning it will coerce between types rather than complain. It is single-threaded with an event loop, so nothing runs in parallel in your code but asynchronous work does not block. It is prototype-based rather than class-based, though class syntax hides that now. And functions are first-class values: you pass them around, return them, and close over variables.
The sharp edges
// coercion produces answers that are correct and useless
[] + {} // "[object Object]"
[] + [] // ""
1 + "1" // "11" number -> string
"5" - 2 // 3 string -> number (but + concatenates!)
// equality has two forms and only one is sane
0 == "" // true == coerces
0 === "" // false === does not. ALWAYS use ===
null == undefined // true
null === undefined // false
// typeof is not reliable
typeof null // "object" a bug from 1995, kept for compatibility
typeof [] // "object" use Array.isArray()
typeof NaN // "number" NaN is a number that equals nothing, including itself
NaN === NaN // false use Number.isNaN()The eight types
Seven primitives — string, number, boolean, null, undefined, symbol, bigint — and everything else is an object, including arrays and functions. There is one number type, a 64-bit float, which is why 0.1 + 0.2 !== 0.3 and why integers above 2⁵³ lose precision (hence bigint).
null versus undefined is a genuine distinction worth keeping: undefined means "never assigned" and is what JavaScript produces itself; null means "deliberately empty" and is what you assign. Most style guides pick one for your own code and let undefined mean the accidental case.
Always use === and !==. The one defensible exception is x == null, which checks for both null and undefined in one go — and even that is clearer written out.
None of these edges are fatal on their own. What makes them expensive is that they surface at runtime, in production, far from the cause — a field that was undefined three function calls ago becomes NaN in a total shown to a user. That distance between cause and symptom is the problem TypeScript is designed to close.
JavaScript vs TypeScript, concretely
TypeScript is JavaScript plus a compile-time type system — same runtime, same semantics, entirely different feedback loop.
The single most important fact: TypeScript is a superset of JavaScript. Every valid .js file is a valid .ts file. TypeScript adds type annotations and a compiler that checks them, then erases them and emits ordinary JavaScript. The browser and Node never see a type.
The difference in one example
// ---------- JavaScript ----------
function total(items) {
return items.reduce((sum, i) => sum + i.price, 0);
}
total([{ price: 10 }, { price: "20" }]); // "1020" ... silently wrong
total(null); // TypeError at RUNTIME, in production
// ---------- TypeScript ----------
type Item = { price: number };
function total(items: Item[]): number {
return items.reduce((sum, i) => sum + i.price, 0);
}
total([{ price: 10 }, { price: "20" }]);
// ^^^^ Type 'string' is not assignable to 'number'
total(null);
// ^^^^ Argument of type 'null' is not assignable to 'Item[]'
// both are COMPILE errors. Neither ships.Side by side
JavaScript TypeScript
typing dynamic, at runtime static, at compile time
errors surface in production in your editor, as you type
refactoring search and hope the compiler finds every call site
IDE support guesswork real autocomplete + go-to-definition
self-documentation comments that rot signatures the compiler enforces
runs in the browser directly after compilation (tsc / esbuild / swc)
runtime behaviour ---------- IDENTICAL ----------
runtime cost ---------- ZERO: types are erased ----------What you actually gain
- Errors move left. The same bug is caught while you type instead of by a user. That is the entire value proposition, and it compounds with codebase size.
- Refactoring becomes mechanical. Rename a field and the compiler lists every place that breaks — which is the difference between a refactor you attempt and one you avoid.
- The signature is the documentation, and unlike a comment it cannot drift out of date.
- Autocomplete that is actually correct, because the editor knows the shape rather than guessing from usage.
What it costs
A build step, some annotation effort, occasional fights with the type system over code that is correct but hard to express, and a learning curve for the team. Those costs are real and front-loaded; the benefits scale with codebase size and team size — which is why TypeScript is close to universal on large projects and genuinely optional on a fifty-line script.
A frequent interview question is "why TypeScript?" and the weak answer is "it catches bugs". The strong answer names the mechanism: it moves a class of error from runtime to compile time, and it makes large-scale refactoring tractable. Then name the cost honestly — a build step and the fact that types are erased, so they guarantee nothing about data arriving from outside your program.
What TypeScript does not do
Types are erased at compile time, so they cannot validate anything that crosses your program's boundary.
This chapter exists because misunderstanding it is the most common and most consequential TypeScript mistake.
Types are erased
// TypeScript
interface User { id: number; name: string }
const u: User = { id: 1, name: "asha" };
// compiles to JavaScript:
const u = { id: 1, name: "asha" };
// the interface is GONE. It does not exist at runtime.Consequences that follow directly: you cannot write if (x instanceof User) for an interface, you cannot iterate a type's fields at runtime, and you cannot make a decision based on a type. Types are a compile-time tool, exactly like a linter that happens to be very sophisticated.
The dangerous case: data from outside
TypeScript trusts you. When you tell it what shape an API response has, it believes you — and it has no way to check.
const res = await fetch('/api/user');
const user: User = await res.json(); // json() returns `any`
// TypeScript now believes user is a User.
// If the API returns { id: "1", nom: "asha" }, TypeScript says NOTHING.
// user.name is undefined at runtime and the type system was no help at all.Every boundary has this problem: HTTP responses, localStorage, URL parameters, form data, environment variables, message queues, and anything from a third-party library typed loosely. Inside your program types are a guarantee; at the edges they are an assumption.
The fix: validate at the boundary
Use a runtime schema validator — Zod, Valibot, io-ts — that both checks the data and infers the TypeScript type from the same definition, so there is one source of truth and it cannot drift.
import { z } from 'zod';
const User = z.object({ id: z.number(), name: z.string() });
type User = z.infer<typeof User>; // the type is DERIVED from the schema
const res = await fetch('/api/user');
const user = User.parse(await res.json());
// throws HERE, at the boundary, with a message naming the field
// - instead of failing three components deep as "undefined is not a function"Validate at the boundary, trust inside. Parse untrusted data once, at the edge, into a known type — then the rest of your program can rely on the type system completely. Chapter 15 goes into this properly.
Two more things TypeScript does not do, worth being able to say: it does not make your code faster (types are erased, so runtime performance is identical), and it does not prevent logic errors — a function typed (a: number, b: number) => number that returns a - b when it should return a + b type-checks perfectly.
Structural typing — the mental model
TypeScript compares types by shape, not by name — which explains most behaviour that surprises people coming from Java or C#.
In Java, a class implements an interface only if it says it does. That is nominal typing. TypeScript is structural: a value is assignable to a type if its shape is compatible, regardless of names, declarations or inheritance.
interface Point { x: number; y: number }
function print(p: Point) { console.log(p.x, p.y); }
const thing = { x: 1, y: 2, colour: "red" };
print(thing); // FINE - it has x and y. The extra property is irrelevant.
class Coordinate { constructor(public x: number, public y: number) {} }
print(new Coordinate(1, 2)); // FINE - it never mentioned PointThis is usually convenient — you do not need to declare conformance, and types compose freely. It becomes surprising in two places.
Surprise 1: excess property checks on literals
Object literals assigned directly get an extra check that variables do not, precisely because a literal with an unexpected property is almost always a typo.
print({ x: 1, y: 2, colour: "red" });
// ^^^^^^ Object literal may only specify known properties
const thing = { x: 1, y: 2, colour: "red" };
print(thing); // fine - the check only applies to fresh literalsSurprise 2: two unrelated types can be interchangeable
type UserId = { value: string };
type OrderId = { value: string };
function load(id: UserId) {}
load({ value: "order-123" } as OrderId); // NO ERROR - identical shapesIf you want them distinguished, you must brand them — add a property that exists only in the type system.
type UserId = string & { readonly __brand: 'UserId' };
type OrderId = string & { readonly __brand: 'OrderId' };
const asUserId = (s: string) => s as UserId;
function load(id: UserId) {}
load(asUserId("u1")); // ok
load("o1" as OrderId); // ERROR - the brands differThink in shapes, not hierarchies. "Does this value have what the function needs?" is the question TypeScript asks — not "was this declared as that type?". Once that clicks, most of the surprising assignability rules stop being surprising.
Branded types are worth knowing for interviews and worth using sparingly in practice — they are excellent for ids, currencies and units where mixing two strings is a real bug class, and they add noise everywhere else. The strong answer names both the technique and when it earns its complexity.
tsconfig and strict mode
Turn on strict, and understand strictNullChecks in particular — it is where most of TypeScript's real value comes from.
Without strict, TypeScript is a much weaker tool. Most of the guarantees people attribute to it come from flags that strict mode enables.
The flags that matter
{
"compilerOptions": {
"strict": true, // turns on the whole family - START HERE
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx", // React 17+ transform: no `import React`
"noUncheckedIndexedAccess": true, // NOT in strict, but you want it
"noEmit": true, // the bundler emits; tsc only type-checks
"skipLibCheck": true, // do not type-check node_modules (much faster)
"isolatedModules": true // required by esbuild/swc transpilers
}
}What strict actually enables
strictNullChecks— the big one. Without it,nullandundefinedare assignable to every type, so the compiler cannot catch the single most common runtime error in JavaScript. With it,stringmeans a string andstring | nullmeans you must handle both.noImplicitAny— a parameter with no annotation and no inferable type becomes an error rather than silentlyany.strictFunctionTypes— checks function parameter types contravariantly, catching a class of unsound callback assignments.strictPropertyInitialization— a class field must be assigned in the constructor or explicitly marked optional.
noUncheckedIndexedAccess
Not part of strict, and worth enabling anyway. It makes indexed access return T | undefined, which is the truth.
const arr: string[] = [];
const first = arr[0];
// without the flag: string <- a lie. It is undefined.
// with the flag: string | undefined <- forces you to handle itAdopting it in an existing codebase
Turning strict on across a large JavaScript codebase produces thousands of errors at once, which is demoralising and gets reverted. The workable path is incremental: enable allowJs and convert file by file, or enable the strict flags one at a time (start with noImplicitAny, then strictNullChecks), fixing as you go.
Start strict on any new project. Retrofitting strictness is far more expensive than beginning with it, and a codebase written without strictNullChecks accumulates assumptions that are painful to unpick later.
Worth knowing for interviews: tsc is usually not what compiles your code any more. Bundlers use esbuild or swc, which strip types without checking them — that is why they are so fast. So tsc --noEmit must run separately in CI, or type errors will ship. That surprises people, and knowing it signals you have set up a real project.
Inference, literals and const
TypeScript infers most types for you — and the difference between let and const changes what it infers.
Annotate less than you think. TypeScript infers from initialisers, return statements and context, and over-annotating adds noise the compiler would have got right.
const n = 5; // 5 <- a LITERAL type, because const cannot change
let m = 5; // number <- let can be reassigned, so it widens
const s = "hello"; // "hello"
let t = "hello"; // string
const arr = [1, 2, 3]; // number[] (contents are still mutable)
const obj = { a: 1 }; // { a: number } <- properties widen, even under constLiteral types
A literal type is a type with exactly one value. On their own they look useless; combined into unions they are one of TypeScript's most valuable features.
type Status = 'idle' | 'loading' | 'success' | 'error';
let s: Status = 'loading';
s = 'lodaing';
// ^^^^^^^^^ Type '"lodaing"' is not assignable to type 'Status'
// a typo that JavaScript would have discovered in productionas const
The as const assertion makes everything in an expression deeply readonly and literal, which is how you get literal types out of objects and arrays.
const config = { mode: 'dark', retries: 3 };
// { mode: string; retries: number }
const config = { mode: 'dark', retries: 3 } as const;
// { readonly mode: "dark"; readonly retries: 3 }
// the most useful application - derive a union from a runtime array:
const ROLES = ['admin', 'editor', 'viewer'] as const;
type Role = typeof ROLES[number]; // 'admin' | 'editor' | 'viewer'
// ONE source of truth: the array you iterate AND the type you check againstThat last pattern is worth remembering. Without it you write the list twice — once as a runtime array and once as a type — and they drift.
When to annotate anyway
- Function parameters — always. There is nothing to infer from.
- Public function return types — often. It documents the contract and stops an accidental change to the body silently changing the API.
- Empty collections —
const items: Item[] = [], or it infersany[]. - When inference is right but unclear to a reader — the compiler is not the only audience.
typeof in a type position is different from the runtime typeof operator: it reads the type of a value, which is how typeof ROLES[number] above works. Pairing it with as const to derive types from data is one of the highest-value small techniques in TypeScript.
Unions, intersections and narrowing
A union is "one of these"; narrowing is how you prove which one — and TypeScript follows ordinary JavaScript checks to do it.
Unions and intersections
type A = { a: string };
type B = { b: number };
type Union = A | B; // has a, OR has b, OR both
type Intersection = A & B; // has a AND b
const u: Union = { a: "x" }; // ok
const i: Intersection = { a: "x", b: 1 }; // must have BOTHThe counter-intuitive part: a union of object types gives you access to fewer properties (only those present on every member), while an intersection gives you more. Union narrows what you can do; intersection widens it.
Narrowing
TypeScript's control-flow analysis understands ordinary JavaScript checks and narrows the type within each branch. You do not need special syntax.
function f(x: string | number | null) {
if (x === null) return; // narrowed OUT: x is string | number below
if (typeof x === 'string') {
x.toUpperCase(); // x is string here
return;
}
x.toFixed(2); // x is number here - by elimination
}
// the ways to narrow:
typeof x === 'string' primitives
Array.isArray(x) arrays
x instanceof Date classes
'name' in x the `in` operator, for object shapes
x.kind === 'circle' a DISCRIMINANT property (chapter 11 - the best one)
x !== null / if (x) truthiness (careful: 0 and "" are falsy)The truthiness trap
function f(count?: number) {
if (!count) return; // BUG: 0 is falsy, so count === 0 exits early
...
}
function f(count?: number) {
if (count === undefined) return; // correct
}Narrowing is lost across callbacks
A frequent frustration: TypeScript cannot prove a variable has not changed by the time a callback runs, so narrowing does not survive into one.
if (user !== null) {
setTimeout(() => user.name, 0);
// ^^^^ 'user' is possibly 'null'
}
// fix: copy into a const, which cannot be reassigned
if (user !== null) {
const u = user;
setTimeout(() => u.name, 0); // fine
}Union types are where TypeScript is genuinely more expressive than most nominal type systems: string | null, 'small' | 'large', and the discriminated unions of Chapter 11 have no clean equivalent in Java without sealed classes. That expressiveness is a good thing to point at when asked what TypeScript is good at.
interface versus type
They overlap almost entirely — use type by default, interface when you need declaration merging or are authoring a library.
This is the most common TypeScript style question and it has a small, real answer.
interface User { id: number; name: string }
type User = { id: number; name: string };
// for object shapes, these are essentially interchangeableWhat only type can do
type ID = string | number; // unions
type Fn = (a: number) => string; // (interfaces can do this, awkwardly)
type Pair = [string, number]; // tuples
type Keys = keyof User; // mapped and conditional types
type Maybe<T> = T | null; // any non-object type aliasWhat only interface can do
// DECLARATION MERGING - two declarations combine
interface Window { myApp: App }
// this ADDS to the global Window type. A `type` cannot do this.
// It is how you augment third-party or global types.
interface Base { a: string }
interface Child extends Base { b: number } // extends reads more naturally
// (type uses & which is fine too)The practical rule
- Use
typeby default. It handles every case, the syntax is uniform, and unions and utility types are where most real modelling happens. - Use
interfacewhen you need declaration merging — augmentingWindow, extending a library's types, or authoring a public API you want consumers to be able to extend. - Be consistent within a codebase. The choice matters far less than mixing both arbitrarily.
One real difference worth knowing
Interfaces are open and lazily resolved, which makes them slightly better for performance in very large codebases and enables merging. Type aliases are eagerly resolved, which produces better error messages for complex computed types. Both effects are marginal until a codebase is very large.
If asked, the answer that lands is: "they are interchangeable for object shapes; type also does unions, tuples and mapped types, and interface also does declaration merging. I default to type and reach for interface when augmenting something." That is complete and takes fifteen seconds.
Generics
A generic is a type parameter — it lets a function or type preserve the relationship between its inputs and outputs.
The motivation is concrete. Without generics, a function that returns whatever it is given must return any, and you lose the type.
function firstBad(arr: any[]): any { return arr[0]; }
const x = firstBad([1, 2, 3]); // any - the type is GONE
function first<T>(arr: T[]): T { return arr[0]; }
const y = first([1, 2, 3]); // number - the relationship is PRESERVED
const z = first(['a', 'b']); // stringConstraints
extends in a generic position is a constraint, not inheritance — it says "T must be at least this", which is what lets you use properties of T inside.
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b; // .length is legal because of the constraint
}
longest('ab', 'cde'); // string
longest([1], [1, 2]); // number[]
// longest(1, 2); // ERROR: number has no `length`keyof and lookup types
The most useful generic pattern in application code — a function that takes an object and one of its own keys, and returns the type of that field.
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: 'asha', active: true };
get(user, 'name'); // string
get(user, 'id'); // number
get(user, 'nope'); // ERROR: not a key of userDefaults and inference
type Result<T = unknown> = { ok: true; data: T } | { ok: false; error: string };
// generics are INFERRED from arguments - you rarely pass them explicitly
first([1,2,3]); // T inferred as number
first<string>([]); // explicit, when inference has nothing to work fromIntroduce a generic only when there is a relationship to preserve — between two parameters, or between a parameter and the return type. A type parameter used exactly once is usually just any wearing a disguise, and you should replace it with a concrete type or a union.
Generics are where TypeScript gets hard, and it is worth being honest about that in an interview. The everyday 90% is what is above; the remaining 10% — conditional types, infer, recursive mapped types — is library-author territory. Knowing where that line is, and not reaching past it in application code, is itself good judgement.
Utility types
Built-in type transformations that let you derive types from other types instead of writing them twice.
The principle behind all of them: never define the same shape twice. Derive variants from one source, and they cannot drift apart.
interface User { id: number; name: string; email: string; createdAt: Date }
Partial<User> // every property optional - for PATCH payloads
Required<User> // every property required
Readonly<User> // every property readonly
Pick<User, 'id' | 'name'> // { id, name } - narrow projections
Omit<User, 'createdAt'> // everything except createdAt - for create payloads
Record<string, User> // { [k: string]: User } - lookup maps
Exclude<A, B> // members of union A not in B
Extract<A, B> // members of union A also in B
NonNullable<T> // removes null and undefined
ReturnType<typeof fn> // the return type of a function
Parameters<typeof fn> // its parameters as a tuple
Awaited<T> // unwraps a PromiseHow they are used in practice
interface User { id: number; name: string; email: string; createdAt: Date }
type CreateUser = Omit<User, 'id' | 'createdAt'>; // the client cannot set these
type UpdateUser = Partial<CreateUser>; // PATCH: all fields optional
type UserSummary = Pick<User, 'id' | 'name'>; // what a list endpoint returns
// add a field to id -> every derived type follows automaticallyWriting your own
They are not magic — they are mapped types, and you can write them. This is worth seeing once so the built-ins stop looking like special syntax.
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
// a genuinely useful custom one: deep partial
type DeepPartial<T> = T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;Derive, do not duplicate. If two types must stay in sync, express one in terms of the other. The compiler then maintains the relationship for you, which is precisely the kind of work you want to hand to a machine.
Note that Omit is not checked against the keys of T — Omit<User, 'nmae'> compiles silently and does nothing. Pick and Exclude are checked. That asymmetry catches people, and a stricter custom Omit with K extends keyof T is a common codebase addition.
Discriminated unions — the most valuable pattern
Give each member of a union a literal tag, and TypeScript can narrow perfectly — making illegal states impossible to represent.
If you take one modelling technique from this book, take this one. It is the closest TypeScript comes to sealed types plus pattern matching, and it eliminates a whole category of bug.
The problem it solves
// the bag-of-optional-fields approach
interface State {
loading: boolean;
data?: User;
error?: Error;
}
// 2 x 2 x 2 = 8 combinations, of which 3 are legal.
// loading AND error? data AND error? neither? All representable. All bugs.
if (!state.loading && state.data) { state.data.name } // ! everywhereThe pattern
type State =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'error'; error: Error }
| { status: 'success'; data: User };
// illegal combinations CANNOT BE CONSTRUCTED. There are exactly four states.
function render(s: State) {
switch (s.status) {
case 'idle': return <Idle />;
case 'loading': return <Spinner />;
case 'error': return <Err error={s.error} />; // error is non-optional HERE
case 'success': return <View data={s.data} />; // data is non-optional HERE
}
}Inside each branch the discriminant tells TypeScript exactly which member you have, so the associated fields are non-optional — no optional chaining, no non-null assertions, no defensive checks.
Exhaustiveness checking
The second benefit, and the one that keeps paying: make the compiler prove you handled every case, so adding a variant later breaks the build at every switch.
function render(s: State): JSX.Element {
switch (s.status) {
case 'idle': return <Idle />;
case 'loading': return <Spinner />;
case 'error': return <Err error={s.error} />;
case 'success': return <View data={s.data} />;
default: {
const _exhaustive: never = s; // ERROR if any case is unhandled
return _exhaustive;
}
}
}
// add { status: 'cancelled' } to State -> this line fails to compileThat never trick works because if every case is handled, the remaining type in default is never — and any missed variant is not assignable to it.
Make illegal states unrepresentable. Whenever you find yourself writing if (!loading && !error && data), the shape is wrong — model the states as a discriminated union and the checks disappear along with the bugs.
This appears constantly in React (Chapter 27 and 48), and it is a strong thing to reach for unprompted in a frontend interview: "I'd model this as a discriminated union so loading-with-an-error can't be represented" takes ten seconds to say and demonstrates real modelling instinct.
any, unknown and never
any switches the type checker off, unknown forces you to prove the type, never means this cannot happen.
any — the escape hatch that spreads
any means "stop checking". Every operation is allowed, and — the part people miss — it is contagious: anything derived from an any is also any, so one annotation can silently disable checking across a whole call chain.
const data: any = JSON.parse(raw);
const name = data.user.profile.name; // no error, whatever the shape
name.toUpperCase(); // no error. Crashes at runtime.
const n: number = name; // no error! any is assignable to anythingunknown — the safe top type
unknown accepts any value, exactly like any — but you can do nothing with it until you narrow it. It is the correct type for genuinely unknown input, and it forces the check that any lets you skip.
const data: unknown = JSON.parse(raw);
data.user; // ERROR: 'data' is of type 'unknown'
if (typeof data === 'object' && data !== null && 'user' in data) {
// now you may proceed - you PROVED something about it
}
// in practice, hand it to a validator (Chapter 15):
const user = UserSchema.parse(data); // unknown -> User, checked at runtimenever — the bottom type
never is the type with no values. It appears in three places, and recognising them is what makes it useful rather than mysterious.
// 1. a function that never returns normally
function fail(msg: string): never { throw new Error(msg); }
// 2. an impossible narrowing - the exhaustiveness check from chapter 11
const _exhaustive: never = s;
// 3. an empty union
type T = string & number; // never - nothing is bothWhere any is defensible
- Migrating a large JavaScript codebase incrementally, with a plan to remove it.
- A genuinely dynamic boundary you validate immediately afterwards — though
unknownis better there. - Working around a bug in a third-party type definition, with a comment explaining why.
Reach for unknown wherever you were about to write any. It accepts the same values and costs you one narrowing step — and that step is exactly the check that would have caught the bug. Then set noImplicitAny and lint against explicit any, so each one is a deliberate, visible decision.
A neat interview question: what is the difference between any and unknown? The crisp answer: both accept any value, but any is also assignable to everything while unknown is assignable to nothing until narrowed. any disables the type system in both directions; unknown only in one.
Type guards and assertions
A type guard is a function whose return value teaches the compiler something — and an assertion is you overruling it.
User-defined type guards
When narrowing logic is reusable or too complex to inline, extract it into a function whose return type is a type predicate: x is T. TypeScript then narrows at the call site.
type Cat = { kind: 'cat'; meow(): void };
type Dog = { kind: 'dog'; bark(): void };
function isCat(a: Cat | Dog): a is Cat { // <- the predicate
return a.kind === 'cat';
}
if (isCat(animal)) {
animal.meow(); // narrowed to Cat
}
// the most useful one in daily code:
function isDefined<T>(v: T | null | undefined): v is T {
return v != null;
}
const clean = items.filter(isDefined); // (T | null)[] -> T[]
// plain .filter(v => v != null) does NOT narrow - the predicate is what does itThat filter(isDefined) example is worth remembering: it is the standard way to remove nulls from an array and have the type reflect it.
Assertion functions
A related form that narrows for everything after the call, by throwing if the assertion fails.
function assertIsUser(v: unknown): asserts v is User {
if (typeof v !== 'object' || v === null || !('id' in v)) {
throw new Error('not a user');
}
}
assertIsUser(data);
data.id; // narrowed from here onType assertions — as
as is different and more dangerous: it is you telling the compiler you know better, with no runtime check whatsoever. It compiles to nothing.
const el = document.getElementById('x') as HTMLInputElement;
// if that element is a <div>, this crashes at runtime and TypeScript said nothing
// safer:
const el = document.getElementById('x');
if (el instanceof HTMLInputElement) { el.value } // an actual check
// the worst form - never do this:
const user = data as unknown as User; // double assertion: pure fictionAnd the non-null assertion ! is the same thing in miniature: user!.name says "trust me, this is not null", with no check.
A type predicate is a claim you verified; as is a claim you asserted. Prefer guards and validators. Every as and every ! is a place where the type system is no longer protecting you — so each one should be rare, deliberate, and ideally commented.
There is one legitimate everyday use of as worth knowing: as const (Chapter 6), which is not an unsafe assertion at all but a request for narrower inference. Beyond that, treat as as a smell that deserves a moment's thought.
Typing third-party and untyped code
Most libraries ship types or have them on DefinitelyTyped; for the rest you write a declaration file, and for globals you use module augmentation.
Where types come from
1. bundled with the package - check for a "types" field in its package.json
2. DefinitelyTyped - npm i -D @types/lodash
3. you write them - a .d.ts file in your project
4. nothing - `any`, with a comment and a planDeclaration files
A .d.ts file contains types only, no implementation. It is how you describe the shape of JavaScript that TypeScript cannot see.
// types/legacy-lib.d.ts
declare module 'legacy-lib' {
export function calculate(a: number, b: number): number;
export const VERSION: string;
}
// the minimum viable escape hatch for an untyped package:
declare module 'some-untyped-lib'; // everything from it becomes `any`
// - unblocks you, but write the real thing when you canNon-code imports
Bundlers let you import images, CSS and SVG; TypeScript needs telling.
declare module '*.svg' {
const content: React.FC<React.SVGProps<SVGSVGElement>>;
export default content;
}
declare module '*.css';Module augmentation and global types
This is where interface earns its keep (Chapter 8): declaration merging lets you add to types you do not own.
// extend a library's type
declare module 'express' {
interface Request { user?: User } // adds to Express's Request
}
// extend a global
declare global {
interface Window { analytics: Analytics }
}
export {}; // required: makes this file a module
// type your environment variables
declare namespace NodeJS {
interface ProcessEnv { API_URL: string; NODE_ENV: 'development' | 'production' }
}When a library's types are wrong, fix them in a declaration file rather than casting at every call site. One augmentation in one place beats fifty as assertions — and it is far easier to remove when the library is fixed upstream.
A practical note: skipLibCheck: true is almost always correct. It skips type-checking inside node_modules, which is much faster and avoids being blocked by errors in someone else's declaration files that you cannot fix anyway.
Runtime validation — where types stop
Types vanish at compile time, so every boundary needs a runtime check — and the right tool derives the type from the schema.
This closes the loop opened in Chapter 3. TypeScript protects the inside of your program; the boundaries are unprotected, and there are more of them than people expect.
every one of these arrives as untrusted data:
HTTP responses localStorage / sessionStorage
URL params and query form submissions
environment variables postMessage / WebSocket messages
file uploads third-party SDK callbacks
anything typed `any` by a librarySchema-first validation
The key property to look for in a validator: it should be a single source of truth that both checks at runtime and produces the static type. Writing an interface and a validator separately guarantees they drift.
import { z } from 'zod';
const UserSchema = z.object({
id: z.number(),
name: z.string().min(1),
email: z.string().email(),
role: z.enum(['admin', 'editor', 'viewer']),
createdAt: z.coerce.date(), // parses the ISO string into a Date
});
type User = z.infer<typeof UserSchema>; // the TYPE is DERIVED from the schema
// parse throws with a field-level message; safeParse returns a result object
const result = UserSchema.safeParse(await res.json());
if (!result.success) {
log.error('contract violation', result.error.issues);
throw new ApiError('Unexpected response from /users');
}
const user = result.data; // fully typed AND actually verifiedWhere to put it
- In the API client, once per endpoint — so every component downstream receives verified data and no component validates anything.
- On form submission, with the same schema the backend uses, so client and server rules cannot diverge.
- On anything read from storage, because it was written by an older version of your app and may not match today's shape.
What good failure looks like
A validation failure at the boundary produces a message naming the field and the expected type, at the exact moment the contract broke. The alternative is undefined is not a function three components deep, twenty minutes of debugging, and a bug report that says "the page is blank".
Parse, do not validate-and-hope. Convert unknown data into a known type at the edge, in one place, and let the type system take over from there. "Parse, don't validate" is the standard phrasing and it is worth knowing by name.
There is a cost: schemas add bundle size (Zod is not tiny) and parsing large payloads is not free. The usual resolution is to validate at genuine trust boundaries only — external APIs and user input — rather than between your own internal modules, where the type system is already sufficient.
Scope, closures and hoisting
A closure is a function plus the variables it captured — and it is the mechanism behind almost every React hook bug.
Scope
var is function-scoped and hoisted; let and const are block-scoped and live in a "temporal dead zone" until their declaration is reached. Use const by default, let when you must reassign, and var never.
// the classic var-in-a-loop bug
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
// 3, 3, 3 - ONE `i`, function-scoped, and it is 3 by the time the callbacks run
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0);
// 0, 1, 2 - `let` creates a NEW binding per iterationClosures
A closure is created whenever a function is defined inside another: the inner function keeps a live reference to the outer function's variables, even after the outer function has returned.
function counter() {
let count = 0; // survives after counter() returns
return { inc: () => ++count, get: () => count };
}
const c = counter();
c.inc(); c.inc();
c.get(); // 2 - `count` is private and persistentWhy this matters enormously in React
Every render creates new function instances that close over that render's values. A callback defined during render captures the props and state as they were at that moment, and keeps them forever — which is exactly right, and exactly why stale closures happen.
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount(count + 1), 1000);
return () => clearInterval(id);
}, []); // <- lying about dependencies
// the effect closed over count === 0 from the FIRST render.
// It computes 0 + 1 forever. The counter sticks at 1.
}
// fix: the functional updater does not need to capture count at all
setCount(c => c + 1);Hoisting
function declarations are fully hoisted and callable before their definition. var declarations are hoisted but initialised to undefined. let, const and class are hoisted but unusable until declared — accessing them earlier throws a ReferenceError.
When a React value looks stale, ask "which render did this function come from?" That single question resolves most stale-closure bugs, and it explains why the dependency array exists: it tells React when to create a fresh closure.
Closures are also how the module pattern, function factories, memoisation and partial application all work — but in a React interview the question is almost always the stale closure. Being able to say "the effect captured the value from the render it was created in" is the answer.
this, and why arrow functions fixed it
In a normal function, this depends on how it is called; in an arrow function it is fixed at definition — which is why arrows are the default in React.
The four binding rules
1. new Foo() -> this is the new object
2. obj.method() -> this is obj (implicit binding)
3. fn.call(x) / bind -> this is x (explicit binding)
4. fn() -> this is undefined in strict mode / globalThis otherwise
resolved in that PRECEDENCE orderThe trap
Rule 2 depends on the call site, not on where the method was defined. So detaching a method loses its this.
const user = {
name: 'asha',
greet() { return `hi ${this.name}`; }
};
user.greet(); // "hi asha"
const g = user.greet; // detached!
g(); // TypeError: cannot read 'name' of undefined
setTimeout(user.greet, 100); // same problem - passed as a bare function
setTimeout(() => user.greet(), 100); // fine - the call site is preservedArrow functions
An arrow function has no this of its own. It uses the this of the enclosing lexical scope, fixed at the moment it is defined and unchangeable — call, apply and bind cannot alter it.
class Timer {
seconds = 0;
start() {
setInterval(function () { this.seconds++ }, 1000); // `this` is wrong
setInterval(() => { this.seconds++ }, 1000); // `this` is the Timer
}
}That is the entire reason class components needed this.handleClick = this.handleClick.bind(this) in constructors — and why class-property arrow functions replaced it.
Where arrows are wrong
- Object methods that need
this— an arrow captures the enclosing scope, not the object. - Prototype methods — same reason.
- Functions needing
arguments— arrows do not have it (use rest parameters). - Constructors — arrows cannot be called with
new.
In modern React you write function components and hooks, so this barely appears — but it still turns up in class-based error boundaries, in third-party libraries, and in interview questions. Default to arrow functions everywhere except object and prototype methods.
A crisp way to state it: a normal function's this is determined by how it is called; an arrow function's is determined by where it is written. That one sentence answers most this questions.
Prototypes and classes
JavaScript inheritance is prototype-based delegation; class is syntax over the same mechanism.
The prototype chain
Every object has an internal link to another object — its prototype. When you access a property, the engine looks on the object, then on its prototype, then on that object's prototype, until it finds it or reaches null. That chain is inheritance in JavaScript: there is no copying, only delegation.
const animal = { speak() { return 'generic noise' } };
const dog = Object.create(animal); // dog's prototype IS animal
dog.bark = () => 'woof';
dog.bark(); // own property
dog.speak(); // not found on dog -> found on animal via the chain
Object.getPrototypeOf(dog) === animal; // trueclass is syntax over this
class Animal {
constructor(name) { this.name = name }
speak() { return `${this.name} makes a noise` } // lives on Animal.prototype
}
class Dog extends Animal {
speak() { return `${super.speak()} - woof` }
}
// methods are on the PROTOTYPE, shared by every instance - not copied per object.
// That is why they are memory-efficient, and why `this` binding matters (ch 17).Why this still matters in a React codebase
- Error boundaries must be classes — there is no hook equivalent of
componentDidCatch, so every React app that handles render errors has at least one class. - Custom Error subclasses —
class ApiError extends Erroris the clean way to model typed failures, and it has a well-known gotcha (below). - Reading library source and older codebases.
- Interview questions, which still ask about the prototype chain.
class ApiError extends Error {
constructor(message: string, public status: number) {
super(message);
this.name = 'ApiError';
// needed when targeting ES5: restores the prototype chain
Object.setPrototypeOf(this, ApiError.prototype);
}
}
// without that line (on ES5 targets), `err instanceof ApiError` is FALSEPrefer composition and plain functions in application code. Classes are right for a small number of things — error types, error boundaries, and stateful objects with genuine invariants — and hooks have replaced them for almost everything else in React.
If asked "how does JavaScript inheritance work?", the strong answer is one sentence: objects delegate to a prototype object, and property lookup walks that chain — class is syntactic sugar over exactly that, not a separate mechanism. Then mention that this is why methods are shared rather than copied per instance.
The event loop
One thread, one call stack, and a queue — plus a microtask queue that always drains before the next macrotask.
JavaScript is single-threaded: there is one call stack, and while it is busy nothing else runs. Asynchrony comes from the runtime (the browser or Node), which does the waiting and queues a callback for when the stack is empty.
call stack runs synchronous code
| empty?
v
MICROTASK queue drained COMPLETELY first
Promise callbacks, queueMicrotask, MutationObserver
|
v
MACROTASK queue ONE task per loop iteration
setTimeout, setInterval, I/O, UI events
|
v
(browser may render here - roughly 60x/second)The ordering question
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// 1, 4, 3, 2
// sync first (1, 4), then ALL microtasks (3), then one macrotask (2)The rule to remember: the entire microtask queue drains before the next macrotask. A promise scheduled inside a microtask runs in the same drain — which is why an infinite chain of promise callbacks starves the loop entirely and freezes the page, while an infinite chain of setTimeout does not.
Why this matters for UI
Because rendering happens between macrotasks, a long synchronous task blocks painting and input. Anything over about 50 ms is a "long task" and shows up directly in the INP metric. That is the mechanism behind every frontend performance rule: break work up, move it to a worker, or defer it.
// blocks the UI for a second - no paint, no clicks
for (let i = 0; i < 1e9; i++) {}
// yields between chunks so the browser can paint and handle input
async function chunked(items) {
for (let i = 0; i < items.length; i++) {
process(items[i]);
if (i % 100 === 0) await new Promise(r => setTimeout(r, 0));
}
}Single-threaded means your code never runs in parallel — so the only way to keep a UI responsive is to keep every task short. That is the whole justification for chunking, transitions, virtualization and Web Workers.
requestAnimationFrame is a third category worth knowing: it runs just before the next paint, which is why it is the right place to batch DOM updates or flush a buffer of incoming WebSocket messages. And requestIdleCallback runs when the loop is otherwise free — good for genuinely low-priority work.
Promises and async/await
A promise is a value that will exist later; async/await is syntax over promises, not a different mechanism.
States and chaining
A promise is pending, then either fulfilled or rejected — and once settled it never changes. .then returns a new promise, which is what makes chaining work.
fetch(url)
.then(res => res.json()) // returns a promise -> flattened automatically
.then(data => use(data))
.catch(err => handle(err)) // catches ANY rejection above it
.finally(() => cleanup()); // runs either wayasync/await
async function load() {
try {
const res = await fetch(url);
if (!res.ok) throw new ApiError(res.status); // fetch does NOT reject on 4xx/5xx!
return await res.json();
} catch (err) {
handle(err);
}
}
// an async function ALWAYS returns a promise
// await pauses this function only - the event loop keeps runningThat res.ok check is a genuine trap: fetch only rejects on network failure. A 404 or 500 resolves successfully, so code that only uses try/catch silently treats an error page as data.
The combinators
Promise.all([a, b, c]) all succeed -> array of results
ANY rejects -> rejects immediately
(the others keep running - not cancelled)
Promise.allSettled([a, b, c]) waits for all; array of {status, value|reason}
-> what you want when partial failure is acceptable
Promise.race([a, b]) first to SETTLE (fulfil or reject) wins
Promise.any([a, b]) first to FULFIL wins; rejects only if all rejectThe sequential-await mistake
// 900ms - three round trips in series
const a = await fetchA();
const b = await fetchB();
const c = await fetchC();
// 300ms - all three in flight at once
const [a, b, c] = await Promise.all([fetchA(), fetchB(), fetchC()]);
// only await sequentially when a later call NEEDS an earlier resultAn unhandled promise rejection is a silent failure. A promise nobody awaits or catches swallows its error — in browsers you get a console warning, in Node it can terminate the process. Always terminate a chain with a handler, and never create a floating promise you do not observe.
Two things that catch people: await inside a forEach does nothing, because forEach ignores the returned promise — use a for...of loop or Promise.all(items.map(...)). And Promise.all rejecting does not cancel the others; JavaScript promises are not cancellable, which is why AbortController exists.
Destructuring, spread and optional chaining
The syntax that makes modern React readable — and two operators whose difference matters.
Destructuring
const { name, age = 18, address: { city } = {} } = user;
// ^^^^ ^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
// pick default nested + rename + default
const [first, , third, ...rest] = items; // skip the second
// in parameters - extremely common in React
function Card({ title, subtitle = '', onClick }) { ... }Spread and rest
const merged = { ...defaults, ...overrides }; // later wins
const appended = [...list, newItem]; // a NEW array
// rest collects the remainder - the standard React props pattern
function Button({ variant, ...rest }) {
return <button className={variant} {...rest} />; // forward everything else
}Spread is a shallow copy. Nested objects are still shared by reference, which matters in the next chapter.
Optional chaining and nullish coalescing
These two are constantly confused, and the difference is exactly the trap from Chapter 1's truthiness discussion.
user?.address?.city // undefined if any link is null/undefined
user?.getName?.() // only calls if it exists
items?.[0] // safe index access
count ?? 10 // 10 only if count is null or undefined
count || 10 // 10 if count is 0, '', false, NaN... <- usually a BUG
// concretely:
const limit = props.limit ?? 20; // limit=0 -> 0 correct
const limit = props.limit || 20; // limit=0 -> 20 wrongUse ?? for defaults, not ||. || falls back on every falsy value, so it silently replaces legitimate zeros, empty strings and false. This is one of the most common real bugs in React codebases, because 0 and '' are perfectly valid values.
One caution on optional chaining: it is easy to over-apply. a?.b?.c?.d everywhere hides the fact that you do not know your own data shape — and after validating at the boundary (Chapter 15) you should not need it internally. Reach for it at genuine boundaries, not as a reflex.
Reference equality and immutability
Objects compare by reference, not contents — which is the single fact behind React re-renders, memoization and dependency arrays.
The fact
{ a: 1 } === { a: 1 } // false - two different objects
[1, 2] === [1, 2] // false
(() => {}) === (() => {}) // false
const x = { a: 1 };
const y = x;
x === y // true - the SAME reference
'abc' === 'abc' // true - primitives compare by VALUEWhy React cares
React decides whether to re-render, re-run an effect, or recompute a memo by comparing values with Object.is — which for objects means reference identity. So a freshly created object is always "changed", even if its contents are identical.
function Parent() {
const style = { margin: 8 }; // NEW object every render
const onClick = () => save(); // NEW function every render
return <MemoChild style={style} onClick={onClick} />;
}
// React.memo compares props by reference -> both differ every time -> memo NEVER hits
// fix: stable identities
const style = useMemo(() => ({ margin: 8 }), []);
const onClick = useCallback(() => save(), []);
// or hoist the constant object outside the component entirelyImmutable updates
React state must be replaced, not mutated — because mutating leaves the reference unchanged, so React sees no change and does not re-render.
// WRONG - same reference, no re-render
items.push(newItem); setItems(items);
user.name = 'new'; setUser(user);
// RIGHT - new reference
setItems([...items, newItem]);
setItems(items.filter(i => i.id !== id));
setItems(items.map(i => i.id === id ? { ...i, done: true } : i));
setUser({ ...user, name: 'new' });
// nested: spread at EVERY level you change (spread is SHALLOW)
setState({ ...state, user: { ...state.user, address: { ...state.user.address, city } } });That nested case is why Immer exists — it lets you write mutating-looking code and produces an immutable update underneath, and it is what Redux Toolkit uses internally.
Never mutate state or props. Replace them. And be aware that this is why deeply nested state is painful — if updates require four levels of spreading, the state shape is usually wrong and should be flattened or normalised.
Worth noting: Object.is is not quite ===. It treats NaN as equal to itself and distinguishes +0 from -0. React uses it precisely so that setting state to NaN twice does not cause an infinite render loop.
Modules: ESM and CommonJS
ESM is static and tree-shakeable; CommonJS is dynamic and is not — and mixing them is the source of a great deal of build pain.
// ESM - the standard, statically analysable
import { thing } from './mod.js';
import Default from './mod.js';
import * as everything from './mod.js';
export const a = 1;
export default fn;
// CommonJS - Node's original system, dynamic
const { thing } = require('./mod');
module.exports = { a };Why the difference matters
- Static versus dynamic. ESM imports are resolved before execution, so a bundler knows exactly what is used.
requirecan be conditional, computed, or inside a function, so it cannot be analysed. - Tree shaking follows from that: a bundler can drop unused ESM exports and cannot drop unused CommonJS ones. A CommonJS-only dependency is dead weight in your bundle.
- Async versus sync. ESM supports top-level
await; CommonJS is synchronous. - Live bindings. ESM imports are live views of the exporting module's bindings; CommonJS copies the value at require time.
Barrel files — a real cost
An index.ts that re-exports everything is convenient and can be expensive: importing one thing from a barrel pulls in the module graph of everything it re-exports, which slows builds and can defeat tree shaking when any of those modules has side effects.
import { Button } from '@/components'; // pulls the whole barrel
import { Button } from '@/components/Button'; // pulls one module
// in package.json, tell bundlers the modules are side-effect free:
{ "sideEffects": false } // or ["*.css"] if you import stylesheetsDynamic import
import() returns a promise and creates a code-splitting boundary — the bundler emits a separate chunk fetched on demand. This is the mechanism behind React's lazy() and every route-based split.
const { heavyThing } = await import('./heavy');
const Editor = lazy(() => import('./Editor')); // ReactUse ESM everywhere and import from the specific module, not the barrel. Those two habits account for a large share of avoidable bundle size — and bundle size is the frontend metric that regresses most silently.
A frequent real-world problem worth recognising: "require() of ES Module not supported" or dual-package hazards, where a library ships both formats and you end up with two copies of it. The fix is usually aligning versions and checking the exports field — and for React specifically, two copies of React is what produces the confusing "invalid hook call" error.
The render model
setState enqueues; the render phase computes a new tree purely; the commit phase applies it — everything else in React follows from that sequence.
React's central idea is that your UI is a function of state. You describe what the screen should look like for the current state, and React works out the minimum DOM operations to get there. You never touch the DOM yourself.
The three steps
1. TRIGGER setState enqueues an update and SCHEDULES work.
Nothing has changed yet. Your local variable is unchanged.
2. RENDER React calls your component function to produce a new element tree,
and diffs it against the previous one.
This phase must be PURE - no side effects, no mutation.
It can be paused, abandoned, or restarted (concurrent rendering).
NOTHING IS ON SCREEN YET.
3. COMMIT React applies the computed mutations to the real DOM in one
synchronous pass, then runs layout effects (useLayoutEffect, refs),
then the browser PAINTS, then passive effects (useEffect) run.Why purity is not optional
Because the render phase can be discarded and re-run, a side effect there executes an unpredictable number of times. Mutating a module-level variable, generating an id, firing an analytics call or starting a fetch during render are all bugs — StrictMode double-invokes components in development precisely to surface them.
State is a snapshot
function handle() {
setCount(count + 1);
setCount(count + 1); // count is STILL 0 in this render -> ends at 1
console.log(count); // 0 - the variable does not change
}
function handleCorrect() {
setCount(c => c + 1);
setCount(c => c + 1); // queued updaters -> ends at 2
}Each render sees its own frozen copy of state. That is not a quirk — it is what makes the closure behaviour in Chapter 16 consistent, and it is why the functional updater exists for cases where the next value depends on the previous.
Batching
Multiple setState calls in the same tick produce one re-render. Before React 18 this only happened inside React event handlers; automatic batching now covers promises, timeouts and native handlers too — so three state updates in an async function cause one render, not three.
When something in React confuses you, walk the three steps. "Why is my value stale?" — you are reading a snapshot from an earlier render. "Why did my effect run twice?" — StrictMode is checking your cleanup. "Why is there a flicker?" — you measured after paint instead of before. The pipeline explains almost everything.
One more consequence worth knowing: if the new state is Object.is-equal to the current value, React bails out and skips the re-render — though it may render once before bailing. That is also why mutating an object and setting the same reference appears to do nothing (Chapter 22).
JSX and elements
JSX is syntax sugar for function calls that produce plain objects — an element is a description, not a DOM node.
// what you write
const el = <button className="primary" onClick={save}>Save</button>;
// what it compiles to (React 17+ automatic runtime)
const el = _jsx('button', { className: 'primary', onClick: save, children: 'Save' });
// what that RETURNS - a plain object
{ type: 'button', props: { className: 'primary', onClick: save, children: 'Save' }, key: null }So an element is a cheap, immutable description of what should be on screen. Creating one does nothing — React compares descriptions and decides what to change. That is why creating elements in a loop is fine and why passing them around as values works.
The rules that trip people up
- Lowercase means a DOM tag; capitalised means a component.
<button>is an element;<Button>is your component. That is why component names must be capitalised. className, notclass, andhtmlFor, notfor— both are reserved words in JavaScript.- One root element per return, because a function returns one value. Use a fragment (
<>...</>) when you do not want a wrapper div. {}embeds an expression, not a statement — so ternaries and&&work, butifandfordo not.- Attributes are camelCase:
onClick,tabIndex,strokeWidth.
What renders and what does not
{null} {undefined} {false} {true} render NOTHING (useful for conditionals)
{0} renders "0" <- the classic bug
{'text'} {42} {[a, b]} render as expected
{ {a: 1} } ERROR - objects are not valid children
// the && trap:
{items.length && <List />} // items.length === 0 renders "0" on the page!
{items.length > 0 && <List />} // correct
{items.length ? <List /> : null} // also correctChildren
children is an ordinary prop that happens to have special syntax. <Card>hello</Card> is exactly <Card children="hello" /> — and understanding that is what makes composition patterns (Chapter 46) make sense.
Remember that JSX is an expression. You can assign it to a variable, put it in an array, return it from a function, or pass it as a prop. Once that clicks, patterns like render props, slots and compound components stop looking like framework magic.
Since React 17 the automatic JSX runtime means you no longer need import React from 'react' in every file — set "jsx": "react-jsx" in tsconfig. Seeing that import in modern code is a small sign the setup is dated.
Components and props
A component is a function from props to elements — and props are read-only, one-way, and the entire communication mechanism.
type Props = {
title: string;
count?: number; // optional
onSelect: (id: string) => void; // callbacks are how children talk UP
children?: React.ReactNode;
};
function Card({ title, count = 0, onSelect, children }: Props) {
return <div><h3>{title}</h3>{count}{children}</div>;
}Props are read-only
A component must never modify its props. Data flows down through props, and events flow up through callbacks — that one-way flow is what makes a React app traceable, because for any piece of state there is exactly one place it lives and one place it changes.
If two siblings need the same value, it moves to their nearest common parent (Chapter 46). If that becomes painful, that is a signal about state placement, not a reason to mutate props.
Composition over configuration
The most important design habit in React: when a component needs to vary its markup, pass elements rather than adding props.
// configuration - every variation needs a new prop, forever
<Card title="x" showIcon iconName="star" badgeText="new" badgeColour="red" />
// composition - the consumer writes what they need
<Card>
<Card.Header>x <Badge>new</Badge></Card.Header>
<Card.Body>...</Card.Body>
</Card>The rule of thumb: if a prop exists to customise rendering, it should probably be composition; if it configures behaviour, it should be a prop.
Two practical patterns
// forwarding the rest of the props to the underlying element
function Button({ variant, ...rest }: Props & React.ComponentPropsWithoutRef<'button'>) {
return <button className={variant} {...rest} />;
}
// consumers get aria-*, data-*, disabled, type - everything - for free
// a component is just a value
const renderRow = (item: Item) => <Row key={item.id} item={item} />;Keep components small and single-purpose. The signals that one is doing too much: more than about ten props, a name containing "and", or a body you have to scroll to read. Splitting is nearly always cheap and nearly always worth it.
Avoid React.FC. It cannot express generic components, it historically added an implicit children prop whether or not you accepted one, and it complicates default props. A plain function with a typed props parameter does everything it does and more (Chapter 41).
State
State is memory that survives re-renders and triggers them — and its shape determines how many bugs you can represent.
const [count, setCount] = useState(0);
const [user, setUser] = useState<User | null>(null);
const [items, setItems] = useState<Item[]>([]);
// lazy initialiser - the function runs ONCE, not on every render
const [state, setState] = useState(() => expensiveInitialValue());
// useState(expensiveInitialValue()) <- WRONG: runs every render, result discardedUpdates are immutable
React compares by reference (Chapter 22), so mutating state does not trigger a re-render. Always produce a new object or array.
setItems([...items, newItem]);
setItems(items.filter(i => i.id !== id));
setItems(items.map(i => i.id === id ? { ...i, done: true } : i));
setUser({ ...user, name: 'new' });Functional updates
When the next value depends on the previous, pass a function. This avoids the stale-snapshot problem and — importantly — removes the value from your effect's dependencies.
setCount(c => c + 1); // correct under batching, and inside closuresShape matters more than anything else
This is the highest-leverage idea in the chapter. A poorly shaped state object can represent illegal combinations; a well-shaped one cannot.
// four booleans -> 16 combinations, 3 of them legal
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error|null>(null);
const [data, setData] = useState<User|null>(null);
// loading AND error? data AND error? Both representable. Both bugs.
// one discriminated union -> exactly four states (chapter 11)
type State =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'error'; error: Error }
| { status: 'success'; data: User };
const [state, setState] = useState<State>({ status: 'idle' });Do not duplicate derivable values
// redundant state that WILL drift out of sync
const [items, setItems] = useState([]);
const [count, setCount] = useState(0); // just items.length
const [filtered, setFiltered] = useState([]); // just a filter of items
// derive during render instead - no state, no sync bug, no effect
const count = items.length;
const filtered = items.filter(matches);Ask two questions of every piece of state: can I derive it? (then do not store it) and can this shape represent something illegal? (then reshape it). Those two questions prevent more React bugs than any amount of careful coding.
Changing a component's key resets all of its state — <Form key={userId} /> gives you a fresh form when the user changes. It is the idiomatic way to reset state on a prop change, and it is much better than an effect that clears fields.
Reconciliation and keys
React matches children by position unless a key overrides it — which is why index keys bind state to the wrong row.
How the diff works
When React compares two element trees, it uses two assumptions to keep the diff O(n) rather than O(n³): different element types produce different trees, and keys tell it which children are the same across renders.
same position, SAME type -> keep the DOM node and component state, update props
same position, DIFFERENT type -> unmount the old subtree entirely, mount fresh
<div><Counter /></div> -> <span><Counter /></span>
// the div became a span, so Counter is DESTROYED and remounted - state lostWhy keys exist
For lists, position is the wrong identity: inserting or reordering shifts everything. A key overrides positional matching, so React matches by key and can move a DOM node instead of rebuilding it — and each item's state follows its key.
The index-key bug, concretely
{items.map((item, i) => <Row key={i} item={item} />)}
// each Row contains an uncontrolled <input>. Now DELETE the first row:
// React sees key 0 still exists (it is now the old second item)
// -> keeps that DOM node and its component state, just updates props
// -> THE USER'S TYPED TEXT STAYS ON THE ROW ABOVE WHERE IT BELONGS
{items.map(item => <Row key={item.id} item={item} />)} // state follows the ITEMThe same mechanism strands checkbox state, focus, scroll position, animation state and anything held inside the row component. It is invisible in a static list and appears the moment users can reorder, filter or delete.
The rules
- Keys must be stable — the same item gets the same key across renders.
- Keys must be unique among siblings, not globally.
key={index}is safe only for a static list that is never reordered, filtered, inserted into or deleted from, and whose items hold no state.- Never
key={Math.random()}— it changes every render, so every row unmounts and remounts, destroying state and performance simultaneously.
A key is an identity, not an index. If your data has no stable id, generate one when the item is created and store it with the item — do not derive it from position.
Keys have a second, deliberate use: forcing a remount. Changing the key of a component destroys and recreates it, clearing all internal state. That is the cleanest way to reset a form when the entity being edited changes, and it is much simpler than an effect that manually clears every field.
Events
React attaches listeners at the root and synthesizes propagation through the React tree — which is why portal events bubble to their React parent.
Delegation
React does not attach a listener to each element. It attaches them at the root container (since React 17; it was document in React 16, which mattered when embedding multiple React apps). When a native event fires and bubbles to the root, React works out which fiber it belongs to and propagates through the React tree, calling your handlers.
The SyntheticEvent you receive is a cross-browser normalised wrapper. Event pooling — which used to require e.persist() — was removed in React 17, so you can hold on to the object.
The portal consequence
function Modal({ children }) {
return createPortal(<div className="modal">{children}</div>, document.body);
}
<div onClick={() => console.log('parent')}>
<Modal><button>Click</button></Modal>
</div>
// clicking the button LOGS 'parent'
// - the modal is elsewhere in the DOM, but events follow the REACT treeThat is usually what you want (a form's onChange still fires for inputs inside a portalled dropdown) and occasionally surprising (a click-outside handler on the parent fires for clicks inside the modal).
Practical patterns
// typed handlers
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setValue(e.target.value);
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); ... };
const onClick = (e: React.MouseEvent<HTMLButtonElement>) => ...;
// capture phase
<div onClickCapture={...}>
// click-outside: use mousedown, and check containment
useEffect(() => {
const onDoc = (e: MouseEvent) => {
if (!ref.current?.contains(e.target as Node)) close();
};
document.addEventListener('mousedown', onDoc);
return () => document.removeEventListener('mousedown', onDoc);
}, []);Using mousedown rather than click for click-outside avoids the opening click immediately closing the menu, and it feels more responsive.
e.stopPropagation() stops React-tree propagation, not native listeners you attached yourself. Mixing React handlers with document.addEventListener is the usual cause of "my dropdown closes the instant it opens" — the two run at different levels.
A common performance question: is it bad to define handlers inline, since they create a new function every render? Usually no — the allocation is trivial. It matters only when the handler is passed to a memoized child or used as an effect dependency, because then the new identity defeats the memo (Chapter 22).
Conditional and list rendering
Conditionals are expressions, lists are map plus keys — and both have one classic trap each.
Conditionals
{isLoggedIn ? <Dashboard /> : <Login />} // either/or
{error && <Error msg={error} />} // render if truthy
{items.length > 0 && <List items={items} />} // explicit comparison
// THE TRAP: 0 is falsy but IS rendered
{items.length && <List />} // renders "0" on the page when empty
{cartCount && <Badge />} // same bugThat is the number-one JSX gotcha. Use an explicit boolean comparison, a ternary with null, or coerce with !!.
Early returns for readability
function Profile({ id }: Props) {
const { data, isPending, error } = useUser(id);
if (isPending) return <Skeleton />;
if (error) return <Error error={error} />;
if (!data) return <Empty />;
return <Details user={data} />; // the happy path, undistracted
}Deeply nested ternaries in JSX are the main readability failure in React codebases. Early returns, or extracting a small component, are almost always better.
Lists
{users.map(user => <UserRow key={user.id} user={user} />)}
// keys on FRAGMENTS need the explicit form
{rows.map(r => (
<React.Fragment key={r.id}>
<dt>{r.term}</dt><dd>{r.def}</dd>
</React.Fragment>
))}
// don't forget the empty state - a bare map renders nothing, silently
{users.length === 0
? <EmptyState />
: users.map(u => <UserRow key={u.id} user={u} />)}Derive, do not store
Filtering and sorting belong in render, computed from state — not in a second piece of state kept in sync by an effect.
// no extra state, no effect, cannot drift
const visible = useMemo(
() => items.filter(i => i.name.includes(query)).sort(byName),
[items, query]
);
// (and only wrap it in useMemo if it is genuinely expensive - chapter 54)Always design the empty state. A list with no items should say something — an empty map renders nothing at all, which is indistinguishable from a failed load. Loading, error and empty are three distinct states and users can tell them apart even when the code cannot.
For very long lists the answer is not cleverer rendering but virtualization (Chapter 55): render only the rows in view. Below a few hundred simple rows it is unnecessary; above a few thousand it is the difference between a usable page and a frozen one.
Forms
Controlled means React owns the value; uncontrolled means the DOM does — and the choice is really about re-render cost versus live derivability.
Controlled
const [email, setEmail] = useState('');
<input value={email} onChange={e => setEmail(e.target.value)} />
// React state is the single source of truth
// + instant validation, derived UI, programmatic control
// - re-renders on EVERY keystrokeUncontrolled
const ref = useRef<HTMLInputElement>(null);
<input ref={ref} defaultValue="" />
// read on submit: ref.current.value
// the DOM holds the value
// + no re-render per keystroke
// - no live derivationThe scaling problem
For a form with forty fields, naive controlled state is the wrong answer, and knowing why is the point: one state object at the form level means every keystroke re-renders all forty fields plus any validation and derived UI. That is where the input lag people complain about comes from.
The scaling answer is subscription-based form state — which is what react-hook-form does. Fields register themselves and are largely uncontrolled; the library holds values in a ref and notifies only the components subscribed to a given field. Typing in field 12 re-renders field 12.
const { register, handleSubmit, formState: { errors } } =
useForm<FormValues>({ resolver: zodResolver(schema) });
<input {...register('email')} /> // typing re-renders THIS field only
{errors.email && <span>{errors.email.message}</span>}
// validation derives from the SAME schema the backend uses (chapter 15)
// -> client and server rules cannot driftPractical details
- Always
e.preventDefault()in a submit handler, or the page reloads. - Validate on blur and on submit by default, switching a field to on-change validation only after it has already failed once — that is the standard UX pattern and it removes most of the work.
- Disable the submit button while submitting, and handle the double-submit case server-side too (an idempotency key).
- Associate every input with a label via
htmlFor— required for accessibility and it makes the label clickable.
Controlled when a field's value drives other UI live — a search box filtering a list, a slider updating a preview. Uncontrolled or subscription-based when it does not. The re-render is the feature in the first case and pure cost in the second.
Client validation is a UX affordance, never a security control — the server must validate regardless. Deriving both from one schema is what makes that duplication safe: the rules exist once, and the client simply gets a faster copy of the same answer.
useEffect — what it is actually for
An effect synchronizes your component with something outside React — it is not a lifecycle hook.
The most common misunderstanding in React is treating useEffect as "run this after render" or "componentDidMount". It is better understood as: keep this external system in sync with my current props and state.
useEffect(() => {
const conn = connect(roomId); // SETUP: sync to the current roomId
return () => conn.disconnect(); // CLEANUP: un-sync from the old one
}, [roomId]); // re-synchronize whenever roomId changesRead that as a loop rather than a lifecycle: whenever roomId changes, React un-syncs from the old room and syncs to the new one. Mount and unmount are just the first and last iterations.
Timing
Effects run after the browser paints, asynchronously, so they never block rendering. Cleanup runs before the next effect and on unmount. That ordering is what makes the synchronization model work — you always un-sync before re-syncing.
What belongs in an effect
- Subscriptions — WebSockets, event listeners, observers, store subscriptions.
- Timers —
setInterval,setTimeout. - Imperative DOM APIs and third-party libraries that manage their own state.
- Data fetching, though a query library is better (Chapter 47).
- Analytics and logging tied to a state change rather than to a user action.
StrictMode and the double mount
In development, React 18 mounts each effect, immediately unmounts it, and mounts it again — producing setup → cleanup → setup. This is deliberate: it surfaces missing or asymmetric cleanup. If your effect is correctly symmetric the sequence is harmless; if it leaks a subscription or double-fires a request, you see it immediately in development rather than as a slow leak in production.
The common complaint "my API is called twice in development" is StrictMode correctly telling you the request has no cancellation.
Every subscribe needs its unsubscribe, in the same effect. Every addEventListener, setInterval, observe and subscribe must have its counterpart in the returned cleanup. That single discipline prevents most memory leaks in a long-lived single-page app.
Do not disable StrictMode because effects run twice — that is removing the smoke detector. If double-mounting breaks something, the effect lacks cleanup or the request lacks cancellation, and that same bug appears in production as a leak or a race.
Dependencies and stale closures
The dependency array declares what the effect reads — it does not choose when the effect runs, and lying about it does not make the code correct.
What the array means
useEffect(fn) // after EVERY render
useEffect(fn, []) // once - the effect reads nothing reactive
useEffect(fn, [a, b]) // whenever a or b changes (compared with Object.is)The mental model that keeps you out of trouble: the array is a list of every reactive value the effect body reads. Props, state, and anything derived from them. It is a declaration of fact, not a scheduling knob.
The stale closure
This is the single most common React bug, and it follows directly from Chapter 16: the effect captures the values from the render in which it was created.
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => setCount(count + 1), 1000);
return () => clearInterval(id);
}, []); // <- LYING: the effect reads `count`
// it captured count === 0 from the first render, forever.
// 0 + 1 = 1, every second. The counter sticks at 1.
}The three honest fixes
// 1. remove the dependency by not needing the value (best when possible)
setCount(c => c + 1); // the updater does not read `count`
useEffect(..., []); // now the empty array is TRUE
// 2. include it, and accept the re-subscription
useEffect(() => { ... }, [count]);
// 3. put it in a ref when it should NOT re-trigger the effect
const latest = useRef(callback);
useEffect(() => { latest.current = callback; }); // updated every render
useEffect(() => {
const id = setInterval(() => latest.current(), 1000); // always the newest
return () => clearInterval(id);
}, []); // subscription is stablePattern 3 is the latest-callback ref, and it is the right tool whenever a long-lived subscription must call a frequently-changing handler without tearing down and rebuilding on every render.
Object and function dependencies
Because comparison is by reference (Chapter 22), an object or function created during render is a new dependency every time — so the effect runs on every render even though nothing meaningful changed.
const options = { id, filter }; // new object every render
useEffect(() => { load(options) }, [options]); // runs EVERY render
// fix: depend on the primitives, or move the object inside the effect
useEffect(() => { load({ id, filter }) }, [id, filter]);Never silence the exhaustive-deps lint rule. It is right essentially always. If including a dependency causes a loop, the fix is one of the three above — not removing it from the array. Lying to the array does not make the code correct; it hides the fact that it is wrong.
A useful diagnostic question when a value looks stale: which render did this function come from? Effects, callbacks and timers all capture the render that created them, and asking that resolves most of these bugs in seconds.
When not to use an effect
Most effects in real codebases should not exist — every one you remove eliminates a render pass and a class of bug.
Effects are for synchronizing with systems outside React. If nothing external is involved, an effect is usually the wrong tool, and the React docs have a page named "You Might Not Need an Effect" for good reason.
1. Do not use an effect to derive state
// WRONG - an extra render, and the two can drift
const [full, setFull] = useState('');
useEffect(() => { setFull(first + ' ' + last) }, [first, last]);
// RIGHT - compute during render
const full = first + ' ' + last;2. Do not use an effect to transform data for display
// WRONG
const [visible, setVisible] = useState([]);
useEffect(() => { setVisible(items.filter(matches)) }, [items, query]);
// RIGHT
const visible = items.filter(matches);
// wrap in useMemo ONLY if profiling shows it is expensive3. Do not use an effect to handle a user event
// WRONG - the effect cannot tell WHY state changed
useEffect(() => { if (submitted) postForm(data) }, [submitted]);
// RIGHT - the handler knows exactly what happened
function onSubmit() { postForm(data); }The distinction: an effect fires because state changed, which could be for any reason. A handler fires because the user did something specific. Event-caused work belongs in the handler.
4. Do not use an effect to reset state on a prop change
// WRONG - renders once with stale state, then again after clearing
useEffect(() => { setDraft('') }, [userId]);
// RIGHT - the key resets everything below it in one pass
<ProfileForm key={userId} userId={userId} />5. Do not chain effects
An effect that sets state which triggers another effect which sets more state produces a cascade of renders and is very hard to follow. Compute the whole result in one place instead.
Before writing an effect, ask: is there an external system involved? A subscription, a timer, the network, the DOM, a third-party library. If the answer is no, the logic almost certainly belongs in render (derived), in an event handler (user-caused), or in a key (reset).
This is a high-signal topic in interviews because it separates people who have used React from people who have debugged it. Being able to say "an effect that sets state which triggers a render is usually a value I should have computed during render" demonstrates real experience with the render model.
useRef
A mutable box that survives renders and never triggers one — for DOM nodes and for values the UI does not display.
const ref = useRef<HTMLInputElement>(null);
<input ref={ref} />
ref.current?.focus();
const timer = useRef<number | null>(null); // mutable, non-render stateThe two jobs
1. Holding a DOM node, for the small number of things that are genuinely imperative: focus, scroll, measure, play a video, or hand an element to a third-party library.
2. Holding mutable state the render output does not depend on — a timer id, a WebSocket, a previous value, an "is this the first render" flag, or the latest-callback pattern from Chapter 33. Storing a timer id in state would re-render on every tick for no reason.
useEffect(() => {
timer.current = window.setInterval(tick, 1000);
return () => { if (timer.current) clearInterval(timer.current); };
}, []);
// previous value
const prev = useRef<number>();
useEffect(() => { prev.current = count; });
// prev.current is the value from the PREVIOUS renderThe rule
Never read or write a ref during render. React does not track ref mutations, so a render-time read can be stale or inconsistent under concurrent rendering — the render output must be a pure function of props, state and context. Refs belong in effects and event handlers.
State or ref?
does the UI need to re-render when this changes?
YES -> useState
NO -> useRef
input value shown to the user -> state
setInterval id -> ref
is the dropdown open -> state
the DOM node of the dropdown -> ref
scroll position used to render a bar -> state (or state + throttle)
scroll position saved for restoration -> refforwardRef and useImperativeHandle
To let a parent hold a ref to a DOM node inside your component, wrap it in forwardRef. To expose a deliberately narrow imperative API instead, use useImperativeHandle — and expose actions, never state, because a handle with setValue() is a second source of truth that will drift from props.
const Player = forwardRef<PlayerHandle, Props>(function Player(props, ref) {
const el = useRef<HTMLVideoElement>(null);
useImperativeHandle(ref, () => ({
play: () => el.current?.play(),
seek: (t: number) => { if (el.current) el.current.currentTime = t; },
}), []);
return <video ref={el} {...props} />;
});The test for imperative versus declarative: is it a moment in time, or a state of the world? "Focus this input now" and "play the video" are moments and fit a ref or a handle. "Is this open" and "which item is selected" are states and belong in props.
React 19 allows passing ref as an ordinary prop to function components, which removes most uses of forwardRef. Worth knowing both, since the forwardRef pattern is everywhere in existing code and in most component libraries.
useContext
Context is dependency injection for a tree — not a state manager, and every consumer re-renders on any change.
const ThemeContext = createContext<Theme>('light');
<ThemeContext.Provider value={theme}>
<App />
</ThemeContext.Provider>
const theme = useContext(ThemeContext); // from the nearest provider aboveHow propagation actually works
A provider stores a value on the fiber tree. Any component calling useContext subscribes to it. When the provider's value changes by reference identity, React re-renders every consumer — and crucially this bypasses React.memo, because context is not a prop.
The two bugs
// 1. a NEW object every render -> every consumer re-renders every time
<Ctx.Provider value={{ user, setUser }}>
// fix: stabilise the identity
const value = useMemo(() => ({ user, setUser }), [user]);
// 2. no granularity - one field changing re-renders everyone reading anything
// fix: SPLIT the context
<StateCtx.Provider value={state}>
<DispatchCtx.Provider value={dispatch}> {/* dispatch is stable forever */}
// components that only dispatch now NEVER re-renderAlways wrap it in a hook
Exporting the raw context invites two problems: consumers get the default value silently when used outside a provider, and the type includes undefined everywhere. A custom hook fixes both.
const Ctx = createContext<AuthValue | null>(null);
export function useAuth() {
const v = useContext(Ctx);
if (!v) throw new Error('useAuth must be used inside <AuthProvider>');
return v; // narrowed to AuthValue - no null checks downstream
}What context is for
Low-frequency values needed widely: theme, locale, the authenticated user, a service client, feature flags. Those change rarely, so a full re-render of consumers costs nothing.
What it is not for: high-frequency state. A form's live value, a mouse position, or anything changing per keystroke in context will re-render the entire consuming tree constantly. That needs a subscription store with selectors (Chapter 40).
Context solves prop drilling, not state management. They look similar and are not: context is a transport mechanism with no granularity, and reaching for it as a store is how applications end up re-rendering everything on every keystroke.
A common follow-up: why doesn't React.memo protect a consumer? Because memo compares props, and context is delivered by subscription rather than as a prop — so a context change bypasses the comparison entirely. That surprises people who have memoized aggressively and still see re-renders.
useReducer
Use it when several fields change together, when the next state depends on the previous in non-trivial ways, or when you want the logic testable outside React.
type Action =
| { type: 'submit' }
| { type: 'success'; data: User }
| { type: 'failure'; errors: Errors };
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'submit': return { status: 'submitting' };
case 'success': return { status: 'success', data: action.data };
case 'failure': return { status: 'error', errors: action.errors };
}
}
const [state, dispatch] = useReducer(reducer, { status: 'idle' });
dispatch({ type: 'submit' });When it beats useState
- Several fields move together. A form with
data,errors,touchedandsubmittingas fouruseStatecalls lets you render illegal combinations — submitting and errored at once. One reducer makes each transition atomic. - The next state depends on the previous in a way that is more than an increment.
- You want the logic tested. A reducer is a pure function:
reducer(state, action). You can test every transition with no rendering at all, which is not true of a tangle ofsetStatecalls. - Dispatch is stable. Its identity never changes, so passing it deep through context causes no re-render churn — unlike a set of callbacks.
Reducers plus discriminated unions
The combination from Chapter 11 is what makes this powerful in TypeScript: type the state as a discriminated union and the actions as another, and the compiler checks that every transition is handled and that each action's payload is correct.
// with `state` as a discriminated union, this is a STATE MACHINE:
// illegal transitions cannot be written, and an unhandled action fails the build
// (add the `never` exhaustiveness check from chapter 11)Keep reducers pure
No fetching, no timers, no logging with side effects, no Date.now() or Math.random(). React may call a reducer more than once to verify purity — StrictMode does exactly that in development. Side effects belong in the event handler that dispatches, or in an effect keyed on the resulting state.
Reach for useReducer when you catch yourself writing three or more setState calls in one handler. That is the reliable signal that the updates belong together as one atomic transition.
It is not faster than useState — both schedule the same work. You choose it for correctness, testability and the stable dispatch, not for performance. Saying that plainly is better than implying an optimisation that does not exist.
useMemo and useCallback
They cache a value and a function identity — and referential equality, not raw computation cost, is usually the real reason to use them.
const sorted = useMemo(() => rows.slice().sort(cmp), [rows, cmp]);
const onSelect = useCallback((id: string) => select(id), [select]);
// they are the same mechanism:
// useCallback(fn, deps) === useMemo(() => fn, deps)The two legitimate reasons
1. The computation is genuinely expensive — sorting or filtering thousands of rows, a heavy derivation — and repeating it every render is measurable.
2. The value is a dependency of something that compares by identity — a React.memo child, a useEffect dependency array, or a context value. This is far more common than reason 1, and it is where the real motivation lies: {} !== {}, so an inline object or function is a new value every render and defeats every memoized consumer downstream.
When they are pure cost
Memoizing a cheap computation whose result nothing compares by identity is strictly worse than not memoizing: you pay an allocation for the dependency array, a comparison on every render, and you add code that must be kept correct — a wrong dependency array turns a performance hint into a stale-value bug.
// pointless
const total = useMemo(() => a + b, [a, b]);
// worth it - stabilises a prop for a memoized child
const onSelect = useCallback(id => setSelected(id), []);
<MemoizedList items={items} onSelect={onSelect} />
// defeated anyway - an inline object is a new identity every render
<MemoizedList items={items} style={{ margin: 8 }} />Two properties worth knowing
useMemois not a semantic guarantee. React may discard memoized values, for example to free memory. Never rely on it for correctness or to avoid re-running something with side effects.- The React Compiler changes the calculus. It inserts memoization automatically, which makes hand-written
useMemoanduseCallbacklargely unnecessary in codebases that adopt it.
Profile first. Add memoization to fix a measured problem, not preemptively. A codebase where everything is wrapped in useMemo is harder to read, no faster, and full of dependency arrays that will drift out of sync with the bodies they belong to.
There is a third, rarer use worth knowing: useMemo to keep a referentially stable object that is expensive to recreate for reasons other than compute — a class instance, a formatter, an observer. Creating a new Intl.NumberFormat on every render is genuinely wasteful, and memoizing it is legitimate.
Custom hooks and the rules
A custom hook is a function that calls other hooks — and the rules exist because hooks are resolved by call order, not by name.
Why the rules exist
This is the mechanism worth knowing, because it makes the rules obvious instead of arbitrary. Hooks are stored in a linked list on the component's fiber and resolved by call order. React has no idea which useState is which — it simply advances a pointer on each call.
// render 1: useState(a) -> slot 0
// useState(b) -> slot 1
// useState(c) -> slot 2
if (condition) { const [a] = useState(1); } // ILLEGAL
const [b] = useState(2);
// when `condition` flips, the sequence shifts and b now reads slot 0 - a's value.
// EVERY subsequent hook is misaligned.Hence the rules: call hooks at the top level only — never inside conditions, loops or nested functions — and only from components or other hooks. The eslint plugin enforces both and is not optional.
What makes a good custom hook
function useDebounced<T>(value: T, delay = 300): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id); // cleanup cancels the pending timer
}, [value, delay]);
return debounced;
}- Extract when logic is stateful AND reused, or when it isolates an external system (a subscription, a media query, localStorage).
- Do not extract pure functions. If it calls no hooks, make it a plain function — easier to test and callable anywhere.
- Name it for the concept, not the mechanism —
useOnlineStatus, notuseEffectWrapper. - Return an object for three or more values, so callers are not order-dependent; a tuple is fine for two.
- Keep returned callbacks stable with
useCallback, so consumers can use them as effect dependencies. - A hook that returns JSX should have been a component.
Hooks share logic, not state
Two components using the same hook each get their own independent state. The hook shares the behaviour, not the data. Sharing state requires lifting it, context, or an external store — a genuinely common misconception worth being clear about.
Custom hooks are also the cleanest way to make a component testable: keep the pure logic in a plain function, the React wiring in the hook, and the markup in the component. Then you can unit-test the logic with no rendering at all, which is much faster and less brittle.
The rest of the hooks
Six more hooks worth knowing, each solving one specific problem.
useLayoutEffect
Same as useEffect but runs synchronously after DOM mutation and before the browser paints. Use it only to measure the DOM and change it before the user sees anything — positioning a tooltip against its trigger, reading and restoring scroll. Do it in useEffect and the browser paints the wrong position first, then you correct it: a visible flicker.
It blocks paint, so heavy work there costs you interaction latency. And it warns during SSR, because there is no layout on the server.
useSyncExternalStore
The integration primitive for state that lives outside React. It solves tearing: concurrent rendering can pause and resume, so two components reading the same mutable store mid-render can see different values and commit an inconsistent UI.
function useOnlineStatus() {
return useSyncExternalStore(
cb => { window.addEventListener('online', cb);
window.addEventListener('offline', cb);
return () => { window.removeEventListener('online', cb);
window.removeEventListener('offline', cb); }; },
() => navigator.onLine, // snapshot - must be referentially STABLE
() => true // server snapshot
);
}
// returning a NEW OBJECT from getSnapshot causes an infinite loopRedux, Zustand and Jotai all use it internally — which is how they became concurrent-safe in React 18. You reach for it directly when subscribing to a browser API, a module-level store, or a WebSocket connection state.
useTransition and useDeferredValue
Both mark work as non-urgent so it can be interrupted by typing or clicking. Use startTransition when you own the state update; use useDeferredValue when you only receive the value as a prop.
const [isPending, startTransition] = useTransition();
setQuery(value); // urgent: the input updates now
startTransition(() => setFilter(value)); // non-urgent: interruptible
const deferred = useDeferredValue(data); // lagging copy for expensive childrenNeither makes rendering faster — they make it interruptible, so typing stays responsive while a heavy list re-renders.
useId and useDebugValue
useId generates a stable unique id that matches between server and client — the correct way to link a label to an input without a hydration mismatch. Never use it as a list key. useDebugValue labels a custom hook in React DevTools.
Two more arriving with React 19 worth knowing by name: useOptimistic for optimistic UI updates with automatic rollback, and useActionState (with the use hook) for form actions and reading promises during render. Both are part of the shift toward Server Components and form actions covered in Chapter 58.
Typing props and children
Type the props object directly, inherit DOM props when wrapping an element, and avoid React.FC.
type Props = {
title: string;
count?: number;
variant: 'primary' | 'secondary'; // a literal union, not string
onSelect: (id: string) => void;
children?: React.ReactNode;
};
function Card({ title, count = 0, variant, onSelect, children }: Props) { ... }Children types, in order of preference
React.ReactNode anything renderable: elements, strings, numbers,
arrays, null, undefined, boolean. <- the default choice
React.ReactElement specifically a JSX element (not a string)
(x: T) => ReactNode a render prop
never explicitly disallow childrenWrapping a DOM element
When your component renders an underlying element, inherit its props rather than listing the handful you thought of. Otherwise consumers cannot pass aria-*, data-*, disabled, type or any other valid attribute.
type ButtonProps = React.ComponentPropsWithoutRef<'button'> & {
variant?: 'primary' | 'secondary';
};
function Button({ variant = 'primary', ...rest }: ButtonProps) {
return <button className={variant} {...rest} />;
}
// consumers now get onClick, disabled, type, aria-label, everything - typedUse ComponentPropsWithoutRef for a plain wrapper and ComponentPropsWithRef when forwarding a ref. For wrapping another component, React.ComponentProps<typeof Other> extracts its props.
Why not React.FC
- It cannot express generic components — a real limitation once you write a
<Select<T>>. - It historically added an implicit
childrenprop whether or not the component accepted one (fixed in React 18 types, but the habit persists). - It complicates
defaultPropsand generic inference for no benefit.
A plain function with a typed props parameter does everything React.FC does and more.
Making illegal props unrepresentable
The same discriminated-union idea from Chapter 11 applies to props, and it is underused.
type Props =
| { variant: 'link'; href: string; onClick?: never }
| { variant: 'button'; onClick: () => void; href?: never };
<Btn variant="link" href="/x" /> // ok
<Btn variant="link" onClick={fn} /> // ERROR - and rightly soPrefer literal unions to string. variant: 'primary' | 'secondary' gives autocomplete, catches typos, and documents the API; variant: string gives none of that and is barely less work to write.
For a component library, also export the prop types (export type ButtonProps = ...). Consumers need them to wrap your components, and not exporting them forces people into ComponentProps<typeof Button> gymnastics.
Typing hooks
Most hooks infer correctly; the ones that need help are useState with a null initial value, refs, and reducers.
const [count, setCount] = useState(0); // number - inferred
const [user, setUser] = useState<User | null>(null); // MUST annotate,
// else inferred as `null`
const [items, setItems] = useState<Item[]>([]); // else `never[]`
// discriminated union state - the pattern from chapter 11
const [state, setState] = useState<State>({ status: 'idle' });Refs — three shapes
// 1. a DOM ref you pass to an element: initialise with null, type includes null
const input = useRef<HTMLInputElement>(null);
input.current?.focus(); // current is readonly here
// 2. a mutable value you own: include undefined in the parameter
const timer = useRef<number | undefined>(undefined);
timer.current = window.setInterval(...); // current is writable
// 3. a ref you are certain is set before use (rare - prefer a null check)
const el = useRef<HTMLDivElement>(null!);The distinction matters: passing null as the initial value makes current readonly (React owns it); passing anything else makes it a mutable box you own.
useReducer
type State = { status: 'idle' } | { status: 'loading' } | { status: 'error'; error: Error };
type Action = { type: 'start' } | { type: 'fail'; error: Error };
function reducer(state: State, action: Action): State { ... }
const [state, dispatch] = useReducer(reducer, { status: 'idle' } satisfies State);
// annotating the reducer's parameters and return type is enough -
// useReducer infers everything from itContext
type AuthValue = { user: User; logout: () => void };
const Ctx = createContext<AuthValue | null>(null);
export function useAuth(): AuthValue {
const v = useContext(Ctx);
if (!v) throw new Error('useAuth must be used inside <AuthProvider>');
return v; // narrowed - consumers never see null
}Typing a custom hook's return
// tuple - use `as const` or the type widens to an array union
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn(o => !o), []);
return [on, toggle] as const; // [boolean, () => void]
}
// without `as const`: (boolean | (() => void))[] - uselessAnnotate when there is nothing to infer from — an empty array, a null initial value, an empty object. Everywhere else, let inference do the work; over-annotating adds noise the compiler would have got right.
The satisfies operator (TypeScript 4.9+) is worth knowing here: it checks a value against a type without widening it, so you get both validation and the narrow inferred type. const config = {...} satisfies Config keeps literal types while still catching mistakes.
Typing events and the DOM
Event types are generic over the element — get that right and target is typed correctly.
React.ChangeEvent<HTMLInputElement> // e.target.value: string
React.ChangeEvent<HTMLSelectElement>
React.ChangeEvent<HTMLTextAreaElement>
React.FormEvent<HTMLFormElement> // onSubmit
React.MouseEvent<HTMLButtonElement>
React.KeyboardEvent<HTMLInputElement> // e.key: string
React.FocusEvent<HTMLInputElement>
React.DragEvent<HTMLDivElement>
React.ClipboardEvent<HTMLInputElement>const onChange = (e: React.ChangeEvent<HTMLInputElement>) => setValue(e.target.value);
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
...
};
const onKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Escape') close();
};Inline handlers are inferred
You only need the annotation when the handler is defined separately. Inline, TypeScript infers the event type from the element, so annotating is noise.
<input onChange={e => setValue(e.target.value)} /> // e is inferred correctlytarget versus currentTarget
A real distinction worth knowing: currentTarget is the element the handler is attached to and is always correctly typed; target is whatever was actually clicked, which may be a descendant, and TypeScript types it as EventTarget.
<div onClick={e => {
e.currentTarget; // HTMLDivElement - the div
e.target; // EventTarget - could be a <span> inside it
}} />
// when you must use target, narrow it properly:
if (e.target instanceof HTMLInputElement) { e.target.value }Native DOM
// getElementById returns HTMLElement | null - narrow, do not assert
const el = document.getElementById('x');
if (el instanceof HTMLInputElement) el.value = 'y';
// native listeners use the DOM event types, NOT the React ones
const onDoc = (e: MouseEvent) => { ... }; // not React.MouseEvent
document.addEventListener('mousedown', onDoc);
// querySelector accepts a type parameter
const input = document.querySelector<HTMLInputElement>('#email');Never type an event handler's parameter as any. It is the most common place any creeps into a React codebase, and it silently removes checking from everything derived from the event — including e.target.value, which is exactly the value you are about to put into state.
If you cannot remember an event type, hover over the JSX prop in your editor — it tells you exactly which type React expects. That is faster and more reliable than memorising the list, and it works for every prop, not just events.
Generic and polymorphic components
A generic component preserves the caller's item type; a polymorphic one changes which element it renders — both are common in design systems.
Generic components
When a component operates on a collection the caller supplies, a type parameter preserves the relationship so callbacks receive the real type rather than unknown.
type SelectProps<T> = {
options: T[];
value: T | null;
getLabel: (item: T) => string;
getKey: (item: T) => string;
onChange: (item: T) => void;
};
function Select<T>({ options, getLabel, onChange }: SelectProps<T>) {
return (
<ul>{options.map(o => (
<li key={getKey(o)} onClick={() => onChange(o)}>{getLabel(o)}</li>
))}</ul>
);
}
<Select options={users} getLabel={u => u.name} onChange={u => ...} />
// ^ u is User - inferredNote this is a case where React.FC simply cannot be used — it has no way to declare a type parameter.
Polymorphic components
A Button that can render as a <button>, an <a>, or a router <Link> — while accepting exactly the props of whichever element it becomes.
type PolymorphicProps<E extends React.ElementType> = {
as?: E;
variant?: 'primary' | 'secondary';
} & Omit<React.ComponentPropsWithoutRef<E>, 'as' | 'variant'>;
function Button<E extends React.ElementType = 'button'>(
{ as, variant = 'primary', ...rest }: PolymorphicProps<E>
) {
const Component = as || 'button';
return <Component className={variant} {...rest} />;
}
<Button onClick={fn} /> // button props
<Button as="a" href="/x" /> // anchor props - href is valid HERE
<Button as="a" onClick={fn} type="submit" /> // ERROR: type is not an anchor propThe honest caveats
- Polymorphic types get complicated fast, and the error messages they produce are among the worst in TypeScript. Weigh that against the benefit.
- Combining generics with
forwardRefis a known rough edge —forwardReferases the type parameter, so you need a cast or a helper function to restore it. - Consider whether you actually need polymorphism. Two clear components (
ButtonandLinkButton) sharing styles is often simpler than one clever one, and much easier to read.
Reach for these in a shared component library, not in application code. Inside an app you usually know the concrete type, and a generic adds indirection for no benefit. The complexity is justified when forty teams consume the component and you cannot enumerate their use cases.
If you write these, invest in the error messages: a constraint like E extends React.ElementType plus a well-named type alias produces far more comprehensible failures than an inline conditional type. Consumers judge a library by what happens when they get it wrong.
Common typing mistakes
Six mistakes that account for most of the friction people attribute to TypeScript itself.
1. any in event handlers
The most common entry point for any in a React codebase. It removes checking from e.target.value — precisely the value heading into your state.
2. Casting instead of narrowing
const el = document.getElementById('x') as HTMLInputElement; // no check at all
const user = data as User; // pure assertion
// narrow, or validate
if (el instanceof HTMLInputElement) { ... }
const user = UserSchema.parse(data);3. Trusting API responses
const user: User = await res.json() is a lie the compiler cannot detect (Chapter 3). Validate at the boundary.
4. Optional props for values that are always present
// makes every consumer handle undefined for no reason
type Props = { user?: User; onSave?: () => void };
// if the parent always passes them, they are required
type Props = { user: User; onSave: () => void };Optionality is contagious: one unnecessary ? forces null checks or ! assertions through everything downstream.
5. Duplicating types instead of deriving them
// two definitions that WILL drift apart
interface User { id: number; name: string; email: string }
interface UserProps { id: number; name: string; email: string }
// derive - one source of truth (chapter 10)
type UserProps = Pick<User, 'id' | 'name'>;
type CreateUser = Omit<User, 'id'>;6. Fighting the compiler when the design is wrong
This is the important one. When a type is genuinely hard to express, that is usually a signal about the shape, not about TypeScript. A props object needing four ! assertions and two casts is telling you the states should be a discriminated union. The compiler complaining is often a design review, not an obstacle.
Treat any, as and ! as the three things to grep for in review. Each one is a place where the type system stopped protecting you, so each should be rare, deliberate and ideally commented. A codebase where they are common has the build cost of TypeScript without the benefit.
Enable @typescript-eslint/no-explicit-any and no-non-null-assertion as warnings rather than errors. That surfaces every occurrence without blocking work, and the warning count becomes a visible measure of type-safety debt that you can drive down over time.
Where state lives
Colocate by default, lift when shared, context for low-frequency wide values, a store for high-frequency or cross-tree state — and the URL for anything shareable.
The ladder
one component uses it -> useState IN that component
two siblings need it -> lift to the lowest common ancestor
needed everywhere, changes rarely -> context (theme, auth, locale)
high-frequency or cross-tree -> external store with SELECTORS
cached server data -> a query library, NOT a store (chapter 47)
shareable / bookmarkable -> the URLColocate by default
State should live in the component that uses it. That keeps re-renders scoped, makes the component self-contained and testable, and means deleting the component deletes its state. Most state should never move.
Lift only as far as necessary
When two components must agree, move the state to their nearest common parent. The cost is that the parent now re-renders on every change — so keep the lift as low as possible, and consider whether the parent can be split so an expensive subtree does not re-render.
The URL is underused state
Anything a user should be able to bookmark, share, or restore with the back button belongs in the URL: the current tab, filters, sort order, page, an open detail id. Putting it in component state instead is a bug users report as "refresh loses my place".
const [params, setParams] = useSearchParams();
const status = params.get('status') ?? 'all';
// shareable, bookmarkable, back-button correct - and freeThe cost of getting it wrong, in both directions
- Too high: unnecessary re-renders across a large subtree, prop drilling through components that do not care, and a parent that becomes a god component.
- Too low: two sources of truth that drift, state lost when a component unmounts (a filter resetting on tab switch), and logic duplicated across siblings.
Prop drilling two or three levels is fine. Reaching for context or a store to avoid passing a prop through one intermediate component adds indirection for no benefit — and makes the data flow harder to follow, which was the thing you were trying to improve.
A useful diagnostic: if a large subtree re-renders when something unrelated changes, the state is in the wrong place. Open the Profiler, find what triggered it, and move the state down or split the component. That is usually a five-minute fix with a large effect.
Server state versus client state
They are different problems — cached server data needs staleness and invalidation, and putting it in a client store is why so many apps have thousands of lines of loading-flag reducers.
The distinction
SERVER STATE CLIENT STATE
you do not own it you own it entirely
can be STALE at any moment always current by definition
shared with other users local to this session
needs caching, refetch, retry needs none of that
asynchronous synchronous
-> a query library -> useState / a store / the URLMost of the complexity people attribute to "state management in React" comes from using one tool for both. A Redux store full of usersLoading, usersError and usersLastFetched is a hand-rolled cache — and caches are hard.
Server state: a query library
const { data, isPending, error } = useQuery({
queryKey: ['orders', { page, status }], // the key encodes EVERY input
queryFn: () => fetchOrders({ page, status }),
staleTime: 30_000,
});The mental model: a cache keyed by query key, with a subscription so components using the same key share one entry and one in-flight request. Get the key right and caching, deduplication and refetching are automatic.
staleTime versus gcTime is the distinction people miss: staleTime is how long data is considered fresh (while fresh, remounting triggers no refetch); gcTime is how long an unused entry stays in memory. The default staleTime of 0 is why beginners see a request on every mount and conclude caching is broken.
After a mutation
queryClient.invalidateQueries({ queryKey: ['orders'] }); // mark stale -> refetch
queryClient.setQueryData(['order', id], updated); // write directly, no round tripClient state: the smallest thing that works
- useState — most of it.
- Context — small, rarely-changing, widely needed (theme, auth).
- Zustand — a store without ceremony: hook-based, selector subscriptions so components re-render only for their slice, usable outside React. The pragmatic default for real client state.
- Redux Toolkit — when you need strict traceable actions, time-travel debugging, complex cross-cutting logic, or enforced conventions for a large team.
Never copy server data into a client store. Read it from the query cache and store only your additions — selection, draft edits, UI state — keyed by entity id. Copying is what creates the synchronisation bug you were trying to avoid.
Asked whether Redux is dead, the honest answer is no — it is no longer the default. It became the wrong tool mainly because people used it to cache server data, which is a problem a query library solves better. For genuinely complex client-side logic in a large app, RTK is still a reasonable choice.
Data fetching: the four bugs
Waterfalls, races, fetch-on-render and missing states — each with a specific fix.
1. Request waterfalls
A parent fetches, renders, and only then does the child mount and start its fetch. Three nested components with a 300 ms API is a 900 ms page for work that could have taken 300.
// serial - 900ms
const user = await fetchUser(id);
const prefs = await fetchPrefs(id);
const orders = await fetchOrders(id);
// parallel - 300ms
const [user, prefs, orders] = await Promise.all([...]);
// structural fix: hoist fetching to the ROUTE, so all requests start
// when navigation begins rather than when components mount2. Race conditions
Props change from A to B; A's request is slow, B's is fast, B lands first, then A overwrites it. The UI shows data for A while the props say B — with no error anywhere. On a fast local connection it never reproduces.
// minimum fix: an ignore flag in the cleanup
useEffect(() => {
let ignore = false;
fetchUser(id).then(u => { if (!ignore) setUser(u); });
return () => { ignore = true; };
}, [id]);
// better: AbortController also cancels the NETWORK work
useEffect(() => {
const c = new AbortController();
fetchUser(id, { signal: c.signal })
.then(setUser)
.catch(e => { if (e.name !== 'AbortError') setError(e); }); // must filter
return () => c.abort();
}, [id]);A query library solves this structurally: responses are keyed, so an out-of-order response for a stale key is discarded automatically and you cannot forget.
3. Fetch-on-render
The component must mount before the request starts, so you always pay one render's delay and get a guaranteed loading flash. The alternative is render-as-you-fetch: start the request when navigation begins — route loaders, prefetch on link hover, or Server Components.
4. Missing states
Loading, error and empty are three different things, and users can tell. An interface that renders nothing on failure is indistinguishable from one that found no results. Model them as a discriminated union (Chapter 11) so the impossible combinations cannot occur.
Use a query library for anything beyond a trivial app. Races, deduplication, caching, retries and background refetch are a solved problem, and hand-rolling them in useEffect means re-solving them in every component — usually incorrectly, and usually invisibly.
Two details worth volunteering: fetch does not reject on 4xx or 5xx, so you must check res.ok yourself or an error page silently becomes your data. And retries should be idempotent-only and capped — retrying a POST without an idempotency key is how you create duplicate orders.
Routing and code splitting
Split at route boundaries and heavy leaves, prefetch on intent, and never replace rendered content with a spinner.
Where to split
Route boundaries first — that is where the user's intent changes and the split is natural. Then heavy leaves regardless of route: a rich text editor, a charting library, a PDF viewer, a date picker with locale data. Those are often larger than the rest of the app combined and used by a minority of sessions.
Do not split small components. Each chunk costs a request and some runtime overhead, and dozens of tiny chunks are slower than a few well-chosen ones — and can create request waterfalls of their own.
const Editor = lazy(() => import('./Editor')); // heavy leaf
<Suspense fallback={<EditorSkeleton />}><Editor /></Suspense>Prefetching removes the cost
// on intent - by the time they click, it is already downloaded
<Link to="/reports"
onMouseEnter={() => import('./routes/Reports')}
onFocus={() => import('./routes/Reports')} />
// also: on viewport entry (IntersectionObserver) for links below the fold,
// and on idle for the one or two most likely next routesFetch the data alongside the code — a route whose JavaScript arrives instantly but then starts its query has only moved the wait.
Avoiding a spinner on every navigation
- Keep the shell persistent — header, nav and layout should never unmount, so only the content region changes.
- Use transitions so React keeps the current page on screen while the next loads, showing a subtle pending indicator rather than tearing down to a fallback.
- Place Suspense boundaries around regions, not the whole page, so a slow widget shows its own skeleton while everything else renders.
const [isPending, startTransition] = useTransition();
startTransition(() => navigate('/reports'));
{isPending && <TopProgressBar />}A fallback should only appear where content has never been shown. Replacing a rendered page with a spinner is a perceived-performance regression even when the measured time is identical — the user had something and now has nothing.
One failure mode to handle: after a deploy, old clients request hashed chunk filenames that no longer exist, so the dynamic import rejects. Catch it in an error boundary and prompt a reload, and keep previous builds' assets available for a grace period so mid-session users are not broken.
Error boundaries and Suspense
Boundaries catch render errors only; Suspense handles pending states — and both should be placed per region rather than per page.
Error boundaries
An error boundary catches errors thrown during rendering, in lifecycle methods, and in constructors of the tree below it. It must still be a class component — there is no hook equivalent of componentDidCatch — which is why most teams use react-error-boundary.
WHAT IT DOES NOT CATCH:
event handlers -> try/catch in the handler
async code (setTimeout, -> .catch() or try/catch in the async function
promise rejections)
server-side rendering
errors thrown IN the boundary itselfThe upside of not catching handler errors: a failed click does not need to unmount your UI. Handle it locally and show a toast.
Suspense
A component suspends while its data or code is pending, and the nearest <Suspense> boundary shows a fallback. Pair every Suspense boundary with an error boundary — one handles "not ready yet", the other handles "it failed" — and they compose naturally because both operate on the tree.
<ErrorBoundary fallback={<FeedError onRetry={refetch} />}>
<Suspense fallback={<FeedSkeleton />}>
<Feed />
</Suspense>
</ErrorBoundary>Granularity is the real decision
One boundary at the page root means any slow call blanks the whole page and any failure kills it. Place a boundary per independent region — sidebar, main content, recommendations — so a failing recommendations service degrades to a small error card while the rest of the page renders normally.
<Layout>
<ErrorBoundary fallback={<SidebarError />}><Sidebar /></ErrorBoundary>
<ErrorBoundary fallback={<MainError />}><Main /></ErrorBoundary>
</Layout>Two things to get right
- Give the fallback a reset action — a
resetKeysarray or an explicit reset so "Try again" actually retries rather than re-showing the cached failure. - Report the error in
componentDidCatch. A boundary that silently swallows failures is worse than a crash, because now nobody knows.
Design skeletons that match the final layout. A fallback with different dimensions causes a layout shift when the content arrives, which is measured directly by CLS and feels worse than a slightly longer wait.
Do not put a boundary around every component. Too many fragments the UI into isolated broken cards and hides systemic failures — if the API is down, twelve small error cards is a worse experience than one honest page-level message. Place them at meaningful product boundaries.
Component API design
Anything that customises markup should be composition; anything that configures behaviour should be a prop.
The god-component failure
A component accumulates a prop per requested variation until it has forty, most combinations are untested, and every new use case requires a change from the owning team. That team becomes a bottleneck, which is an organisational problem before it is a technical one.
Compound components
Share implicit state through context so consumers assemble the markup themselves.
<Select value={v} onChange={setV}>
<Select.Trigger placeholder="Choose" />
<Select.Options>
{items.map(i => (
<Select.Option key={i.id} value={i.id}>
{i.label} {i.isNew && <Badge>New</Badge>} {/* no new prop needed */}
</Select.Option>
))}
</Select.Options>
</Select>Headless components
Go further: a hook owns behaviour, state and accessibility and returns state plus prop-getters, rendering nothing. The consumer owns 100% of the markup. That is the TanStack and Radix-primitives model, and it lets one behavioural implementation serve completely different visual designs.
Controlled and uncontrolled duality
// value provided -> the consumer controls it; omitted -> the component manages it
function useControllable<T>(value: T | undefined, defaultValue: T) {
const [internal, setInternal] = useState(defaultValue);
const isControlled = value !== undefined;
return [isControlled ? value : internal,
isControlled ? () => {} : setInternal] as const;
}
// simple cases need no state; a sort order that lives in the URL is equally supportedThe refactoring rule
props that customise RENDERING -> composition (Select.Option, Table.Cell)
props that configure BEHAVIOUR -> props (multiple, disabled, sortable)
props that are STATE -> props, with controlled/uncontrolled duality
if you are adding a `render*` prop, the answer was compositionBuild accessibility into the core, not into each consumer. A shared Select whose keyboard handling, roving tabindex and ARIA wiring live in the hook means forty teams get it right by default — and that is the strongest single argument for owning a shared component at all.
The honest cost of composition: the API becomes implicit. There is no props table listing what is possible, so documentation and examples matter far more, and consumers can assemble it incorrectly — so make your context hook throw a clear error when a subcomponent is used outside its parent.
State machines for complex flows
Booleans multiply into illegal states; a machine enumerates the legal ones and makes the rest unrepresentable.
The arithmetic
A checkout flow with isLoading, hasError, isPaid, isRetrying and isConfirmed has 2⁵ = 32 combinations, of which perhaps six are legal. The other 26 are reachable by a mistimed update, and each is a bug someone will eventually report as "the button was disabled and the spinner ran forever".
The machine
const machine = {
idle: { SUBMIT: 'authorizing' },
authorizing: { OK: 'succeeded', FAIL: 'declined', TIMEOUT: 'unknown' },
declined: { RETRY: 'authorizing', CANCEL: 'cancelled' },
unknown: { POLL_OK: 'succeeded', POLL_FAIL: 'declined' },
succeeded: {}, // terminal
cancelled: {}, // terminal
} as const;
function reducer(state: State, event: Event): State {
const next = machine[state.name][event.type];
return next ? { ...state, name: next } : state; // unknown event -> IGNORED
}What it eliminates structurally
- Double submission is impossible —
authorizinghas noSUBMITtransition. - A late webhook cannot revive a cancelled flow —
cancelledis terminal, so the event is ignored by definition rather than by a guard someone might forget. - The
unknownstate is modelled explicitly — a payment timeout is neither success nor failure, and a boolean-based design has nowhere to put it.
That last point matters beyond the frontend: the ambiguous timeout is a real distributed-systems problem, and a machine gives it a home rather than forcing it into a boolean.
Testable and diagrammable
The transition table is a pure function you can test exhaustively with no rendering — and it can be drawn, so a designer, a QA engineer and a backend developer can look at one diagram and agree on what the flow does. That shared artefact is worth as much as the bug prevention.
useReducer or XState?
useReducer is enough for most flows — a switch on (state, event). Reach for XState when you need hierarchical or parallel states, delayed transitions, invoked services with cancellation, or the visualiser. And keep side effects out of the reducer: the machine decides what state we are in, and effects are triggered by entering a state.
The threshold is roughly four or more states with non-trivial transitions, or any flow involving money, external systems or retries — where an illegal state has real consequences. Below that, useState is fine and a machine is ceremony.
Model the waiting states explicitly, including timeouts. authorizing needs a TIMEOUT transition, because a payment gateway that never responds is a real state your UI must handle — and it is exactly the state that boolean-based designs leave undefined.
Diagnosing before optimising
Establish which of three problems you have — too many renders, renders that are too slow, or a blocked main thread — because each has a completely different fix.
Guessing is why most React performance work achieves nothing. People sprinkle useMemo everywhere and the page is still slow, because the actual cost was a long task that had nothing to do with rendering.
The three problems
1. TOO MANY RENDERS many small renders of components whose output did not change
cause: identity - inline objects/functions, context, state placed too high
fix: stabilise identities, split context, move state down, selectors
2. RENDERS TOO SLOW few renders, each expensive
cause: rendering thousands of nodes, or an expensive derivation per render
fix: virtualization, memoized derivations, render less
3. MAIN THREAD BLOCKED it is not React at all
cause: a long task - parsing JSON, a third-party script, layout thrash
fix: Web Worker, chunking, remove the scriptThe React Profiler
Record the interaction, then read the commit list. The flame graph shows what rendered and how long each took; the ranked chart sorts by duration. For each expensive component, DevTools tells you why it rendered — props changed, state changed, parent re-rendered, or a hook changed. That single piece of information usually points straight at the fix.
Enable "Record why each component rendered" in the Profiler settings — it is off by default and it is the most useful thing in the panel.
When it is not React
If the Profiler shows nothing rendering but the page still stutters, switch to the browser's Performance panel and look for long tasks — anything over 50 ms blocks input and paint (Chapter 19). Common culprits: parsing a large JSON response, a third-party analytics or chat script, synchronous localStorage access, and layout thrashing from reading and writing DOM geometry in a loop.
Measure in the field
Lab profiling on a fast laptop hides the p75 experience on a mid-range Android over 4G. Ship the web-vitals library, report to your analytics, and set targets on the field p75 — that is what users actually have, and what search ranking uses.
import { onINP, onLCP, onCLS } from 'web-vitals';
onINP(m => beacon({ metric: 'INP', value: m.value, route }));Never optimise without a measurement, and never leave without a guard. A bundle-size budget in CI and RUM alerts on p75 are what stop the fix decaying over the next two quarters — otherwise you will do this work again.
A useful first check on a slow list: does every row re-render when one item changes? If so it is problem 1 (identity or state placement), and virtualization will not help — it will just render fewer wrong things. Getting that triage right saves days.
Memoization done right
React.memo compares props shallowly — and three very common patterns silently defeat it.
const Row = React.memo(function Row({ item, onSelect }: Props) { ... });
// skips re-rendering if every prop is Object.is-equal to last render'sThe three silent failures
- Inline object, array or function props.
style={{margin: 8}},items={[...]}oronClick={() => …}create a new identity every parent render, so the shallow comparison always fails. You pay for the comparison and get nothing. childrenas JSX.<Memoized><Child /></Memoized>passes a new element object every render —childrenis a prop like any other, so the memo never hits.- Context. A consumer re-renders when its context value changes regardless of memo, because it subscribes to the provider directly rather than receiving a prop.
// defeated
<Row item={item} onSelect={() => select(item.id)} style={{ padding: 4 }} />
// works
const onSelect = useCallback((id: string) => select(id), []);
const style = useMemo(() => ({ padding: 4 }), []);
<Row item={item} onSelect={onSelect} style={style} />
// better still: hoist genuinely constant objects OUT of the component
const STYLE = { padding: 4 };Custom comparators — usually a mistake
React.memo(Row, (prev, next) => prev.item.id === next.item.id) looks efficient and is dangerous: it compares fewer fields than the component reads, so a real change is skipped and the UI silently goes stale. It is also easy to make more expensive than the render you avoided. Fix prop identity instead.
Selector granularity
For store-based state, the highest-leverage technique is not memo at all — it is subscribing to a slice so a component only re-renders when its own data changes.
const name = useStore(s => s.user.name); // re-renders only when name changes
const user = useStore(s => s.user); // re-renders on ANY user field changeThe React Compiler
This changes the calculus. The compiler analyses your components and inserts memoization automatically, which makes hand-written useMemo, useCallback and React.memo largely unnecessary in codebases that adopt it. It relies on your components being pure — which is exactly what the rules of React have always required, and why StrictMode exists to enforce them.
Memoize to fix a measured problem, not preemptively. Verify in the Profiler that the memo actually removed renders — a memo that never hits is pure overhead plus a false sense of having optimized, and it adds a dependency array that will drift.
If you adopt the React Compiler, the most valuable preparation is making components genuinely pure: no mutation during render, no reading refs in render, no side effects. Code that already follows the rules gets the benefit automatically; code that does not is where the compiler bails out.
Virtualization
Render only the rows in view — the maths is simple for fixed heights and needs a measurement cache for variable ones.
A hundred thousand rows means a hundred thousand DOM nodes at mount and a diff over all of them on every render. The page freezes for seconds. Virtualization renders perhaps thirty.
The fixed-height maths
const rowHeight = 40, overscan = 4;
const start = Math.max(0, Math.floor(scrollTop / rowHeight) - overscan);
const visible = Math.ceil(viewportHeight / rowHeight) + overscan * 2;
const rows = items.slice(start, start + visible);
<div onScroll={e => setScrollTop(e.currentTarget.scrollTop)}
style={{ overflowY: 'auto', height: viewportHeight }}>
{/* spacer gives the scrollbar the correct size */}
<div style={{ height: items.length * rowHeight, position: 'relative' }}>
{rows.map((item, i) => (
<div key={item.id}
style={{ position: 'absolute', top: (start + i) * rowHeight,
height: rowHeight }}>
{item.name}
</div>
))}
</div>
</div>Overscan — rendering a few extra rows above and below — is what prevents blank flashes during fast scrolling, because scroll events fire after the paint. Three to five rows is typical.
Variable heights
Qualitatively harder, because you can no longer compute an index from an offset. You need a measurement cache: render with an estimated height, measure actual heights with ResizeObserver as rows mount, store them, and maintain a prefix-sum of offsets so you can binary-search from scrollTop to the start index. Total height becomes an estimate that converges — which is why naive implementations have a scrollbar that shifts slightly as you scroll.
The hard parts
- Accessibility — screen readers and browser find-in-page only see rendered rows. Set
aria-setsizeandaria-posinsetso assistive tech knows the real list length, and accept that Ctrl+F will not find off-screen text. - Scroll restoration — persist
scrollTopand restore it after the container has its full height, or you set a position larger than the current content and the browser clamps it to the top. - Keyboard focus — moving focus to a row that is not rendered requires scrolling it into view first, then focusing on the next frame.
- Sticky headers and pinned columns fight absolute positioning and usually need a separate synchronized layer.
Below a few hundred simple rows, do not virtualize. The overhead and the complexity are not repaid, and pagination or simply rendering less per row is often the better answer. Measure first — this is a technique with a real maintenance cost.
In practice use TanStack Virtual or react-window rather than hand-rolling. The value of knowing the maths is being able to explain the mechanism, reason about the variable-height case, and debug it when the library behaves unexpectedly — not to write it yourself.
Concurrent React and Core Web Vitals
Transitions make rendering interruptible rather than faster — and INP is the metric that measures whether the main thread is free.
Interruptible rendering
Concurrent React can start rendering, pause, abandon and resume. That is what lets an urgent update — a keystroke — preempt a non-urgent one, and it is why the render phase must be pure (Chapter 24).
// I own the state update -> startTransition
const [isPending, startTransition] = useTransition();
function onChange(e) {
setQuery(e.target.value); // urgent: input updates now
startTransition(() => setFilter(e.target.value)); // non-urgent: interruptible
}
{isPending && <Spinner subtle />}
// I only receive the value -> useDeferredValue
const deferred = useDeferredValue(data);
return <ExpensiveChart data={deferred} />;Neither makes the work faster. If a render genuinely takes 800 ms, the result still arrives in 800 ms — it just no longer blocks typing. If the work is that expensive, virtualize or memoize as well.
Core Web Vitals
LCP Largest Contentful Paint < 2.5s when the main content appears
usually an IMAGE, FONT or render-blocking resource - rarely React
INP Interaction to Next Paint < 200ms interaction -> next painted frame
replaced FID; measures input delay + processing + presentation
-> long tasks AND expensive renders both show up here
CLS Cumulative Layout Shift < 0.1 unexpected movement
unsized images, injected content, fallbacks of the wrong size
all measured at the FIELD p75, not in the labFixing each
- LCP — preload the hero image with
fetchpriority="high", neverloading="lazy"above the fold,font-display: swapplus a preloaded woff2, remove render-blocking scripts. Note LCP cannot beat your TTFB. - INP — break up long tasks, move heavy work to a worker, use transitions for expensive updates, and audit third-party scripts (often the largest single cause).
- CLS — set explicit
widthandheighton images and media, reserve space for anything injected, and make skeletons the same size as the content they replace.
Why did FID become INP? FID measured only the delay before the handler started, so a page could score well while the handler took 500 ms and the UI froze. INP measures the whole interaction through to the next paint — which is what the user actually experiences.
The most common React-specific INP cause is a state update that triggers a large re-render synchronously inside a handler — a filter over ten thousand rows on every keystroke. That is exactly what transitions and useDeferredValue exist for, and it is the clearest case where a concurrent feature fixes a measurable metric.
Rendering strategies and hydration
Five strategies chosen by content type — and hydration is O(entire tree), which is what makes a page visible but unresponsive.
CSR ship an empty shell, render in the browser
+ simple, cheap hosting - poor first paint, poor SEO
SSR render HTML per request on the server
+ good first paint and SEO - server compute, TTFB tied to your data
SSG render at build time
+ fastest, CDN-cacheable - content fixed until the next build
ISR SSG + background regeneration after a TTL
+ static speed, fresh-ish content
STREAMING SSR send the shell immediately, stream regions as data resolves
+ LCP no longer waits for the slowest queryChoosing
- Marketing page → SSG
- Product catalogue that changes daily → ISR
- Dashboard behind a login → CSR or SSR; SEO is irrelevant
- Content page where first paint matters and data is slow → streaming SSR
Hydration
The client re-runs the component tree over the server-rendered HTML to attach event handlers and rebuild internal state. The cost is that it is O(entire tree), not O(interactive parts) — so a page can be visible but unresponsive while hydration runs, which is precisely what INP measures.
Hydration mismatch
If the server and client render different output, React discards the server HTML and re-renders on the client — silently throwing away the entire benefit of SSR.
causes:
Date.now() / Math.random() during render
reading window, localStorage or navigator during render
locale or timezone differences between server and client
browser extensions modifying the DOM before hydration
fix: render the deterministic version on both sides, then apply the
client-only value in an EFFECT after mount
(suppressHydrationWarning for genuinely unavoidable cases like a timestamp)// the standard pattern for client-only values
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
return <span>{mounted ? new Date().toLocaleString() : null}</span>;SSR is not free. It moves work to your servers, ties your TTFB to your slowest query, and adds a whole class of hydration bug. Choose it because you need first paint or SEO — not because it sounds more sophisticated than CSR.
Streaming SSR with Suspense is the refinement worth knowing: split the loader's data into critical (awaited, so the route does not render without it) and non-critical (streamed in behind a Suspense boundary). The order detail renders immediately while the slow related-items query resolves separately, so the slowest query no longer sets the page's time to content.
React Server Components
Server Components run only on the server and ship zero JavaScript — so bundle size scales with interactivity rather than with page size.
The mental model
An RSC executes on the server during rendering, can access the database directly, and sends a serialized description of the UI rather than code. Client Components — marked 'use client' — are the ones that ship JavaScript and hydrate.
SERVER data fetching (query the DB directly - no API layer needed)
secrets and API keys
heavy dependencies (markdown, syntax highlighting, date libraries)
anything that would otherwise bloat the bundle
CLIENT state, effects, event handlers, browser APIs
anything using useState, useEffect, or contextThe boundary rule
'use client' is infectious downward: everything imported by a client component becomes part of the client bundle. So push the boundary as deep as possible. The most common adoption mistake is marking a whole page as client because one button needs onClick.
// server component (the default) - queries directly, ships no JS
async function OrderPage({ params }) {
const order = await db.order.findUnique({ where: { id: params.id } });
return (
<Layout>
<OrderSummary order={order} /> {/* server: static, no JS */}
<ActionsPanel orderId={order.id}> {/* client: needs onClick */}
<OrderTimeline order={order} /> {/* SERVER, passed as children! */}
</ActionsPanel>
</Layout>
);
}That last line is the key pattern: a client component can receive server components as children, because the server renders them to elements before passing them. So an interactive shell can wrap server-rendered content without making it client. What a client component cannot do is import a server component.
Serialization
Props crossing the boundary must be serializable: primitives, plain objects, arrays, dates, and JSX. Functions and class instances cannot cross — which surprises people passing a callback down.
The honest assessment
RSCs genuinely solve two real problems: client-side data-fetching waterfalls, and bundle size that grows with page complexity. The costs are a new mental model, serialization constraints, harder debugging across the boundary, and an ecosystem still catching up. They pay off most for content-heavy applications and least for highly interactive dashboards where almost everything is client anyway.
RSCs do not replace SSR — they compose with it. SSR is about producing HTML for the initial response; RSCs are about which components ever ship JavaScript. You typically use both, plus streaming.
Server Actions are the write-side counterpart: a function marked 'use server' that a client component can call directly, with the framework handling the network round trip. Combined with useActionState and useOptimistic, that is the direction React is moving — worth knowing by name even if you are not using it yet.
Accessibility
Use semantic elements, manage focus, and make everything keyboard-operable — that covers the overwhelming majority of real accessibility.
Semantic HTML first
The single highest-leverage rule: use the right element. A <button> is focusable, activates on Enter and Space, announces itself as a button, and works with every assistive technology. A <div onClick> does none of that, and reproducing it correctly takes four attributes and two handlers.
<div onClick={save}>Save</div> // invisible to keyboards
<button onClick={save}>Save</button> // correct, free
<div className="heading">Title</div> // no structure
<h2>Title</h2> // navigable landmark
nav, main, header, footer, ul/li, label + input, table
-> all give structure that screen readers navigate byFocus management
The area React apps get wrong most often, because the DOM changes without a page load.
- Modals — move focus in on open (to the first meaningful element, never a destructive button), trap Tab inside, close on Escape, and restore focus to the trigger on close. Losing focus to
document.bodystrands keyboard users at the top of the page. - Route changes — focus the main heading and announce the new page, or a screen-reader user has no idea anything happened.
- The
inertattribute removes a subtree from the tab order, hit testing and the accessibility tree in one step — it replaces the old error-prone combination ofaria-hiddenplus manualtabindex.
ARIA — the first rule
The first rule of ARIA is not to use ARIA. Prefer a native element. When you must build a custom widget, follow the ARIA Authoring Practices pattern exactly — a half-implemented combobox is worse than a plain <select>.
// announcing async changes - otherwise a screen reader hears nothing
<div aria-live="polite" className="sr-only">{statusMessage}</div>
// the combobox pattern: focus STAYS in the input,
// aria-activedescendant tells assistive tech which option is highlighted
<input role="combobox" aria-expanded={open} aria-controls="list"
aria-activedescendant={active >= 0 ? `opt-${active}` : undefined} />The cheap wins
- Every input has a
<label htmlFor>. - Every image has
alt— emptyalt=""for decorative ones. - Colour is never the only signal (roughly 8% of men have a colour vision deficiency).
- Text contrast meets 4.5:1, and focus indicators are visible — never
outline: nonewithout a replacement. - Respect
prefers-reduced-motion.
Test with the keyboard. Unplug the mouse and complete your main flow using only Tab, Enter, Space, arrows and Escape. That five-minute test finds more real problems than any automated tool, because automated scans catch perhaps a third of issues.
In interviews, accessibility is the most commonly skipped and most cheaply scored area. Mentioning semantic elements, focus restoration and a live region for async updates — unprompted, in the last two minutes — reads immediately as production experience.
Testing
Test behaviour through the accessible tree, intercept at the network layer, and prefer integration tests over isolated units.
The guiding principle
React Testing Library's premise: the more your tests resemble how the software is used, the more confidence they give you. So query by accessible role and name rather than by test id or class — and the side benefit is real, because a test that can only find your button by role is also asserting the button is accessible.
screen.getByRole('button', { name: /save/i }) // preferred
screen.getByLabelText('Email')
screen.getByText(/no results/i)
screen.getByTestId('x') // last resort
await screen.findByText(...) // retries until it appears - use for async
queryBy... // returns null instead of throwing - for absenceMock the network, not your modules
Use MSW to intercept at the network layer rather than mocking your fetch wrapper or query client. Tests then exercise the real data-fetching code path, survive a refactor from fetch to axios, and let you assert loading, error and empty states by returning the corresponding responses.
const server = setupServer(
http.get('/api/orders', () => HttpResponse.json({ items: [] }))
);
test('shows the empty state', async () => {
render(<Orders />);
expect(await screen.findByText(/no orders yet/i)).toBeInTheDocument();
});
test('submits the form', async () => {
const user = userEvent.setup();
render(<OrderForm />);
await user.type(screen.getByRole('textbox', { name: /reference/i }), 'INV-1');
await user.click(screen.getByRole('button', { name: /save/i }));
expect(await screen.findByText(/saved/i)).toBeInTheDocument();
});What to test, and what never to
- Test: user-visible behaviour and the component's contract — does an invalid form show errors, does clicking Save call the API and show success, does the empty state appear.
- Never test: internal state values, whether a specific hook ran, class names, or large snapshots. A snapshot that changes on every refactor gets regenerated without being read, so it asserts nothing while adding review noise.
- Extract pure logic — formatting, validation, reducers — into plain functions and unit-test those directly. They need no DOM and run in microseconds.
Shape of the pyramid
For React specifically, favour integration over isolated unit tests: a component rendered with its real children and a mocked network is far more valuable than each child tested alone with everything stubbed. Then a small number of E2E tests (Playwright) for critical journeys.
Use userEvent, not fireEvent. It simulates the full sequence a real user generates — pointer, focus, keydown, input — and catches bugs a synthetic change event misses entirely, such as a handler that depends on focus.
Flaky E2E tests are the main failure mode, and blind retries are the wrong answer — they hide real race conditions. Quarantine the test, give it an owner and a deadline, and fix or delete it. A suite people re-run until it passes has stopped being a signal.
Frontend security
React escapes text by default, which is not the same as being XSS-proof — and CSRF depends entirely on how you authenticate.
XSS in React
JSX escapes interpolated values, so {userInput} is safe. That lulls people into thinking React is immune. It is not — there are three real vectors.
1. dangerouslySetInnerHTML with unsanitized input
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />
2. URL attributes - href/src accept javascript: and data: URLs
const SAFE = /^(https?:|mailto:)/i;
<a href={SAFE.test(url) ? url : '#'}>...</a>
// ALLOWLIST the scheme - blocklists lose to encoding
3. spreading server data onto a DOM element
<div {...propsFromServer} /> // can inject event handlersContent Security Policy
The defence-in-depth layer — and it only works if you avoid unsafe-inline. A policy containing script-src 'self' 'unsafe-inline' provides almost no protection, because injected inline script is exactly what XSS produces.
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-{random}'; <- nonces, NOT unsafe-inline
object-src 'none';
base-uri 'self'; <- blocks base-tag injection
frame-ancestors 'none'; <- clickjacking
deploy as Content-Security-Policy-Report-Only first, collect violations,
then enforce - or you will break your own siteCSRF applies only with cookie auth
This is the distinction people miss. If you send a bearer token in an Authorization header, a cross-site form post cannot add that header, so CSRF is structurally impossible. With cookies, the browser attaches them automatically — so you need SameSite=Lax or Strict plus a double-submit token for the cases SameSite does not cover.
Token storage — no free option
localStorage convenient, works across tabs
READABLE BY ANY JAVASCRIPT -> one XSS anywhere exfiltrates it
httpOnly cookie invisible to JavaScript -> XSS cannot read it
sent automatically -> requires CSRF protection
in memory only most secure; lost on refresh
-> pair with a refresh token in an httpOnly cookie
(the common production answer)Say the trade-off rather than picking one silently. There is no option without a cost, and an interviewer asking about token storage is checking whether you know that — not whether you memorised a winner.
Two more worth naming: keep third-party scripts minimal and use Subresource Integrity, because a compromised analytics tag runs with your origin's full privileges; and never put secrets in client-side code — everything shipped to the browser is public, including anything in your environment variables that the bundler inlined.
The frontend interview
Frontend rounds are deliberately vague, and they score how you handle ambiguity more than what you can recall.
The order to work in
1. SCOPE ask; then state what you WILL build and what you'll only describe
2. API + STATE the response shape, then the state SHAPE (discriminated union)
3. HAPPY PATH get something rendering early
4. STATES loading / error / empty <- most commonly missed
5. A11Y semantics, labels, keyboard, focus, live region <- 2nd most missed
6. PERF debounce, cancel, memo, virtualize - only if warranted, and SAY WHY
7. CLOSE "with more time I'd add X and Y"Steps 4 and 5 are the cheapest points available. Both take two minutes and both read immediately as production experience — an interface that renders nothing on failure is indistinguishable from one that found no results, and pointing that out yourself is a strong signal.
Narrate continuously
Frontend rounds tempt you into heads-down coding because there is visible output on screen. The interviewer still needs to hear the reasoning. Say the tradeoff as you make it: "I'm debouncing the request rather than the input so typing stays instant", "I could lift this but it would re-render every row, so I'll colocate it". A decision they did not hear you make cannot be scored.
The concepts most often probed
- The render model — what happens between
setStateand the DOM updating. - Keys and reconciliation — and the concrete index-key bug.
- Effect timing and stale closures — and when not to use an effect.
- Why context re-renders every consumer and bypasses
React.memo. - The four data-fetching bugs — waterfalls, races, fetch-on-render, missing states.
- TypeScript: discriminated unions,
unknownversusany, and why types are erased at runtime.
How to answer
- Lead with the mechanism, not the symptom. "Hooks are a positional linked list on the fiber" explains all four rules of hooks; reciting the rules explains nothing.
- Name the failure the feature prevents. "Without stable keys, deleting a row leaves the typed text on the wrong row" beats a definition of reconciliation.
- Volunteer the cost. Every technique trades something, and naming the trade unprompted is the clearest senior signal available.
- Say when you do not know, then reason from what you do. "I have not used RSCs in production, but based on how the boundary works I would expect…" is a strong answer; inventing detail is the only guaranteed failure.
An interview is a conversation between two engineers about a problem, not an examination. Ask clarifying questions, state your assumptions, think out loud, and react to what the interviewer says. Candidates who engage rather than perform consistently do better — and if you have worked through this book, you have the material to engage with.