Skip to content
Tech Interview Prep
Technical interview guide

React Fundamentals

The rendering model, state as a snapshot, keys and component identity, effects as synchronization, memoisation, and the client boundary.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: React 19, including automatic batching from React 18 and the Server Component model as implemented by React 19 and Next.js 16.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-2

How would you reason about components as pure functions of props and state in a system you own?

Answer

The contract. A component's render must be a pure function of its inputs: props, state, context, and any store snapshot it reads. Same inputs, same output, no observable side effects. That is not a style preference: React's render phase is allowed to run any number of times, be interrupted, restarted, or thrown away. StrictMode double-invokes every component in development to surface violations. Concurrent rendering can start a render, abandon it, and start again. React Compiler memoizes on the assumption that render is pure. If your render writes to anything outside itself, the output depends on how many times React happened to call it, and that count is not part of your contract.

Where the boundary sits. Render phase: compute. Commit phase: effects, refs, event handlers: touch the world. Anything that must vary between renders (a timestamp, a random id, a subscription) comes in as an input or is read in an effect, never generated during render.

Trace: the double-invoke.

JSX
let renders = 0;                       // module scope

function Counter({ step }) {
  renders += 1;                        // write during render
  const [n, setN] = useState(0);
  return <button onClick={() => setN(n + step)}>{n} (render #{renders})</button>;
}

Mount under <StrictMode> in dev: React invokes Counter twice and keeps the second result. renders goes 1 → 2, so the committed DOM reads 0 (render #2). In production, a single invoke gives 0 (render #1). Same props, same state, different output: the definition of impure. A test that renders once and asserts on the string passes in CI and fails the moment StrictMode is on.

Trace: the bailout. Purity also governs how you update state.

JSX
const [items, setItems] = useState([{ id: 1, done: false }]);

function toggle(id) {
  const next = items;                          // same array reference
  next.find(i => i.id === id).done = true;     // mutate in place
  setItems(next);                              // Object.is(next, items) === true
}

React compares the new state to the old with Object.is. Same reference → it bails out, no re-render, the checkbox stays stale. The fix is to produce a new object: setItems(items.map(i => i.id === id ? { ...i, done: !i.done } : i)).

Where each kind of value belongs.

ValueHomeWhy
Derived from props/statecomputed in render (useMemo only if measured hot)always consistent with inputs
Mutable, not part of output (timer id, DOM node, previous value)useRefsurvives renders, doesn't trigger one
External storeuseSyncExternalStoreReact reads a snapshot, no tearing
Sync with the outside world (fetch, subscription, DOM)useEffectruns after commit; may run twice in dev

Trade-offs. Purity costs recomputation: every render redoes the work. useMemo, useCallback and React.memo are caches layered on a pure function: they change cost, not semantics, and they only work if the function is pure. Reach for them when a profile shows the recompute is the bottleneck, not by default. The escape hatch for genuinely imperative work (canvas, focus management, a charting library) is a ref plus an effect, not a render-phase write.

In a system you own, make the contract enforceable rather than aspirational: StrictMode on in dev, eslint-plugin-react-hooks and the React Compiler lint rules failing the build, and at least one test that renders a component twice and asserts identical output. That last one catches the class of bug that otherwise only appears under a fast refresh or a concurrent interruption.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through props as a read-only argument, including where engineers most often get it wrong.

Answer

Core answer

Props are the read-only inputs a parent passes when it renders a child. The automatic JSX runtime (react/jsx-runtime, what CRA, Next.js and Vite configure by default) compiles <List items={x} /> to _jsx(List, { items: x }); the classic React.createElement(Type, props, ...children) path is opt-in. Either way React allocates a fresh props object per element: one object per element, so a 10,000-row list allocates 10,000 props objects on every render pass. Data flows one way: the parent owns the value, the child reads it.

In development React calls Object.freeze on each element's props (and on the element itself) inside ReactJSXElement. That freeze is shallow and O(k) in the number of own keys: it never touches nested objects. Production builds skip it entirely.

So props.title = 'x' throws TypeError: Cannot assign to read only property 'title' in dev, because ES modules are strict mode and frozen writes throw rather than no-op. In production the same line succeeds and mutates the props object: worse than throwing, since React diffs the previous element's props against the next element's props, and you just edited the previous one.

Failure 1: mutating through a prop

The shallow freeze is the trap. props.items.push(x) is legal: the array isn't frozen. If items is the parent's state array, you mutated the parent's data without calling a setter, so no render is scheduled.

JSX
function List({ items }) {
  items.push('new'); // mutates the parent's state array in place
  return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
}

Trace it. Parent state is items = ['a']. The parent renders, passing that same array reference. List pushes 'new', so the parent's state array is now ['a', 'new'], but no setter ran, so React schedules nothing and the DOM still shows a. Later an unrelated parent update re-renders and the list jumps to a, new. Hypothetical cost: a 5,000-row list at roughly 0.05 ms per row is ~250 ms of commit work landing on an interaction the user didn't connect to the list. That delay is why it survives casual testing.

Fix: setItems(prev => [...prev, 'new']) in the parent, or pass an onAdd callback up.

Failure 2: prop copied into state

JSX
function Frozen({ name }) {
  const [value, setValue] = useState(name);
  return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}

useState(name) reads name on the first render only. The argument expression is still evaluated on every render and thrown away, so useState(expensiveParse(text)) pays the parse every time: use the lazy form useState(() => expensiveParse(text)). When the parent later passes a new name, Frozen keeps the first one.

Fixes: derive directly (value={name}) when the child doesn't own the value; or key={name} to remount, which discards state, re-runs effects, recreates DOM nodes and drops focus and scroll position; or sync in an effect, the last resort, because it commits twice per prop change. Once with the stale value, once after the effect.

Failure 3: new identity every render

React.memo compares props shallowly with Object.is per key: O(k) for k props, one level deep. <Row style={{ color: 'red' }} onPick={() => pick(id)} /> allocates a new object and a new closure every render, so memo never hits and the child re-renders anyway. Hoist the object, or wrap the callback in useCallback.

React 19 notes. defaultProps on function components was removed (deprecated in 18.3); use default parameters. ref is now an ordinary prop, so forwardRef is unnecessary.

When to lift. Lift to the closest common parent when two components read or write the value; pass the value down and an updater up. Prop-initialised state is only for genuine starting points, such as an uncontrolled form's default. The rule: props are read-only, and if a child needs to change a value, the change belongs to whoever owns the state.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does state as a snapshot of one render guarantee, and what does it deliberately leave open?

Answer

Guarantee: for the duration of one render, the value returned by useState is a constant. The setter does not write to it. Every closure created during that render (event handlers, effects, timers, promises) reads the same value, no matter when it later runs.

Left open: when the re-render happens, how many renders it takes, whether the render commits, and what the next value is. The setter queues an update; the next render sees the result of applying the whole queue to the previous state, not the argument you passed.

JSX
function Counter() {
  const [n, setN] = useState(0);
  console.log('render', n);
  function onClick() {
    setN(n + 1);
    setN(n + 1);
    setN(n + 1);
    console.log('handler sees', n);
  }
  return <button onClick={onClick}>{n}</button>;
}

Trace, React 18, StrictMode off:

  1. Mount: logs render 0, button reads 0.
  2. Click: the handler is the one created by the mount render, so n is 0. Logs handler sees 0. Three updates are queued, each carrying the literal 1.
  3. React applies the queue: 0 → 1. The value changed, so it re-renders. Logs render 1, button reads 1.

Swap the three calls for setN(x => x + 1) and the queue is 0 → 1 → 2 → 3: one re-render, render 3. Same number of renders, different result: the render count was never the contract.

GuaranteedLeft open
The binding is fixed for the render that created itWhen the re-render is scheduled, and what it batches with
Setters queue an update instead of mutatingHow many times the component renders: bailouts, StrictMode's double invoke, concurrent re-renders
Every closure from that render sees the same valueWhether the render commits to the DOM
The next render sees the queue applied to the previous stateWhether the update lands at all if the component unmounts first

Failure modes:

  • Stale closure. A handler stored in a ref, or a setTimeout scheduled during an earlier render, reads that render's value forever. Detect it by logging the value inside the callback next to the value on screen; they diverge.
  • Double-apply. Two setN(n + 1) calls in one handler move the count by one. Detect it with a handler that increments twice and a test asserting the delta.
  • Read-after-set. setN(n + 1); if (n > 0) … branches on the old value. The if belongs in the next render or in an effect.

What to do: use the updater form whenever the next value depends on the previous one; pull the value into a const if a handler needs it more than once; read state in the next render rather than after the setter. If you need the value outside render (in a timer, a subscription, a ref) copy it into a ref in an effect, which is the escape hatch the snapshot model leaves you.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain render as a calculation, commit as the write and how it changes a production decision.

Answer

The 90-second version

Render is React calling your function components to compute a description of the UI: a tree of React elements. Commit is the separate, synchronous phase where React takes the tree it kept and writes it to the host environment: DOM mutations, ref attachment, layout effects, then passive effects.

The contract that matters: render may run zero, one, or many times for a single update, and React is free to throw a render away. Commit runs exactly once per committed update and is not interruptible. So render has to be a pure calculation (same props and state, same output, no writes anywhere) and commit is the only place writes are allowed to land.

Why the split exists

Concurrent rendering. React can start rendering a low-priority update, get interrupted by a keystroke, discard the partial work, and re-render at higher priority. Discarding is only safe if the render did nothing observable. That is the whole reason purity is a rule and not a style preference.

The production decision it changes

Where side effects live, and whether memoization is safe to add.

JSX
// Wrong: the write is part of the calculation
function Viewed({ id }) {
  analytics.track("viewed", id);   // runs per render attempt
  return <span>{id}</span>;
}

// Right: the write is caused by an interaction
function Viewed({ id }) {
  useEffect(() => { analytics.track("viewed", id); }, [id]);
  return <span>{id}</span>;
}

Trace for one update that changes id from 1 to 2, in development under StrictMode:

PhaseCalls
render (component body)2
commit (DOM mutation)1
passive effect1

Two track calls for one user action. In production StrictMode does not double-invoke, so the body version fires once, which is exactly why this survives testing and ships. On mount, StrictMode also runs the effect twice (setup, cleanup, setup), so an effect that subscribes must return a cleanup or you leak a subscription per mount.

The trap memoization springs

Because render is a calculation, React.memo is a cache of that calculation: equal props, no render. If the write lives in the body, adding React.memo changes how many times the write happens: the count becomes a function of prop equality instead of user actions. Wrapping a component in memo to fix a perf problem can silently halve your analytics. That is a production decision, not a lint rule.

Failure modes and how you see them

  • Duplicate writes: event count exceeds user-action count. Log a render counter and a commit counter side by side in dev; a 2:1 ratio on each update is StrictMode, not a React bug.
  • Dropped writes after memoization: event count falls after a memo change. Diff the counts before and after.
  • Corrupted shared state: pushing to a module-level array during render leaves entries for UI that was never committed. Assert the array length equals the commit count.
  • Stale reads: refs are attached during commit, so a ref read during render is null on first render and stale afterwards.

When not to use an effect

Interaction-caused writes belong in the event handler: an effect runs after paint and re-runs on dependency change, which is the wrong trigger for "user clicked". Reach for useLayoutEffect only when you must read or write layout before the browser paints; it blocks paint. Everything else is a passive effect.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Describe updater functions against captured values and the evidence you would collect before relying on it.

Answer

Short answer. setN(prev => prev + 1) queues a function that React runs later, during the next render, with whatever value the queue has accumulated by then. setN(n + 1) queues a value computed now, from the n captured in the current render's closure. When two updates land in the same batch, the captured-value form can only ever produce the value it computed from the stale snapshot; the updater form composes.

What the queue does. React collects actions in order and folds them at render time. A plain value is a replace action; an updater is a function applied to the running result.

JSX
function Counter() {
  const [n, setN] = useState(0);
  return (
    <button onClick={() => {
      setN(n + 1);              // replace with 1
      setN(n + 1);              // replace with 1 (same captured n)
      setN(prev => prev + 1);   // 1 -> 2
    }}>{n}</button>
  );
}

Render starts at n = 0, so the closure's n is 0 for both plain calls. Queue: [1, 1, prev => prev + 1]. Fold: 1, 1, 2. The next render shows 2, not 3.

Evidence before relying on it. Don't take the slogan on faith; collect these.

  1. Version and batching scope. React 18 auto-batches updates in promises, setTimeout, and native handlers; React 17 batches only inside React event handlers. A test that passes in onClick can fail in a setTimeout on 17. Record the React version and where the update originates.
  2. Render count. React DevTools Profiler: two setN calls in one handler should produce one render on 18. If you see two, batching isn't happening and the captured-value bug may not reproduce.
  3. StrictMode double-invoke. In React 18 dev, StrictMode calls updater functions twice. If a console.log or array push inside the updater fires twice, the updater is impure: that's the evidence, and it's a real bug, not a StrictMode artifact.
  4. A failing-then-passing test. Fire two updates in one tick and assert the final value. This is the only evidence that the stale read actually bites in your code path.
  5. Log both values. console.log(n, prev) inside the updater shows the gap between the closure snapshot and the queued state.

Failure modes. Escaping to a ref or module variable to dodge the stale value replaces a scheduling problem with an invisible one: the ref doesn't trigger a render, so the UI keeps showing the old state, and it survives casual testing because the happy path hides it. Stale closures in setInterval or websocket handlers are the same bug with a longer fuse.

When not to use it. State set from an external source (a form field, a fetched payload, a reset) is a replacement, not a derivation; the plain value is correct and the updater adds nothing.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on automatic batching of updates. How do you evaluate it?

Answer

What I'd ask first: does the design need batching for correctness, or only for cost? Those get evaluated differently. If it needs batching to be correct: "one effect run per batch", "one fetch per batch", "one analytics event per batch": the design is resting on a scheduling behavior, and I'd push back. If it only needs batching to keep renders down, it's a performance question you can measure and fall back from.

Then check the assumption against the runtime it ships on. Automatic batching is React 18 behavior, and it's tied to the root API:

ContextBatched?
React 18 createRoot / hydrateRoot; updates in event handlers, promises, setTimeout, native handlersyes
React 17 and earlier, or React 18 with legacy ReactDOM.renderonly inside React event handlers; a promise or setTimeout update renders immediately
Any update separated from the previous one by an awaitno: later tick, separate render
Updates split by flushSyncno: flushSync commits the pending work, so the surrounding updates are no longer one batch
React Native / react-test-renderer on React 18yes, same automatic batching

So "we rely on batching" is a claim that has to name the root API and the React version. A design that is correct on createRoot and wrong on legacy render is a migration hazard, not a design.

Trace the actual update sequence. This is the cheapest way to falsify the assumption:

JSX
async function load() {
  setA(1);
  setB(2);          // same tick as setA
  await fetch('/x');
  setC(3);
  setD(4);          // same tick as setC, but a later tick than setA/setB
}

Two renders: one with A=1, B=2, one with C=3, D=4. Not one. If the design assumed a single commit per load(), it's wrong, and the bug surfaces as a doubled effect, a doubled request, or a doubled log line, not as a crash.

Batching also doesn't coalesce values. Two setCount(count + 1) calls in one handler batch into one render that still only adds 1, because both read the same count. If the design hinges on batching to "merge" increments, it needs functional updates (setCount(c => c + 1)), which is a different fix.

Failure modes and how to catch them:

  • Correctness tied to commit count breaks the moment an await, a flushSync, or a legacy root splits the batch. Detect with a render counter or the Profiler's commit count in a test, not by eyeballing.
  • A DOM measurement taken between two setters reads the pre-update layout. Detect by asserting the measured value after the commit, or move the read into useLayoutEffect.
  • Dev/prod divergence: StrictMode double-invokes render and effects in development, so a design that counts renders or effects looks different in dev. Test the behavior, not the count.

Verdict: accept the design if batching is load-bearing only for cost, and require it to stay correct with batching disabled. Separate ticks, legacy root, flushSync in the path. If it's load-bearing for correctness, ask for the invariant to be enforced explicitly (functional updates, one effect keyed on the batch, an explicit debounce) rather than inherited from the scheduler.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Where does lazy initial state matter, and where is it irrelevant?

Answer

The 60-second answer

useState's argument is evaluated on every render; React keeps only the first result. So useState(parseCsv(text)) parses the CSV on every render and throws away every parse but the first. Passing a function, useState(() => parseCsv(text)), defers the call to the render that creates the state.

Lazy initial state matters when the initial value is expensive to compute and cheap to defer: parsing, JSON.parse(localStorage.getItem(...)), building a lookup index, constructing a Worker or an AudioContext, reading layout. It is irrelevant when the initial value is a literal or a cheap primitive: useState(0), useState(''), useState({}). Wrapping those in a function buys nothing and allocates a closure per render.

JSX
// React 18/19
function Report({ text }) {
  // parseCsv runs on every render; all but the first result are discarded
  const [rows, setRows] = useState(parseCsv(text));

  // parseCsv runs once, on mount
  const [rows2, setRows2] = useState(() => parseCsv(text));

  // same trap for refs: new Worker(url) runs on every render
  const bad = useRef(new Worker(url));

  // created once, on mount
  const ref = useRef(null);
  if (ref.current === null) ref.current = new Worker(url);
}

Say parseCsv takes 12 ms on a 2 MB file (hypothetical). A form that re-renders 50 times while the user types pays 600 ms of main-thread work to produce one value it already had. That is the whole cost of the eager form, and it is invisible in a test that renders once.

What lazy initial state does not do

  • It does not memoize derived values. useMemo recomputes when its dependencies change; a lazy initializer runs once for the lifetime of the mount and never again. If the value should track text, lazy init is the wrong tool.
  • It does not survive a remount. Changing a key, or unmounting and remounting the component, pays the cost again.
  • It does not read fresh props. The initializer closes over the props of the first render only; later prop changes do not update state.
  • It does not make an impure initializer safe. In development StrictMode React calls the initializer twice to surface impurity, so it must be pure: no network calls, no counters, no mutations of outer state. Production calls it once.

Two cases where the function form is mandatory, not an optimisation

Storing a function in state: useState(handler) would call handler and store its return value. useState(() => handler) stores the function itself.

Refs holding costly objects: useRef(new Worker(url)) constructs a Worker on every render and keeps the first, leaking the rest. The null-check pattern above is the ref equivalent of the lazy initializer.

How to decide

Ask whether the value is a literal. If it is, pass it directly. If it is not, pass the function: the cost of the closure is negligible next to any real initialisation, and the failure mode of guessing wrong is silent per-render work. Then measure: if the initializer shows up in a profile, it is expensive; if it never does, the wrapper was free insurance.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach derived values computed rather than stored to an engineer who has only seen it as a rule of thumb.

Answer

The 60-second version. A value that can be computed from props or state should be computed during render, not stored. Storing it creates a second source of truth that can disagree with the first, and the disagreement stays invisible until the inputs change in a way your test didn't cover. Keep in state only what you cannot derive: the user's raw input, the ids of things they selected, and data that arrived from outside React. Filtered lists, totals, validity flags and formatted strings are computed on the way out.

The mechanism is that render is already a pure function of props and state. A stored copy needs a second mechanism, an effect, to keep it in sync, and effects run after paint. That gap is where the stale value shows.

JSX
// React 18
function SearchList({ items, query }) {
  const [visible, setVisible] = useState(items);
  useEffect(() => {
    setVisible(items.filter(i => i.name.includes(query)));
  }, [items, query]);
  return <List rows={visible} />;
}

Trace it with items = [{name:'ada'},{name:'bob'}], query = '':

  1. Render 1: visible is the initial state, the full list. React commits and paints two rows.
  2. Effect runs. filter returns a new array holding the same two objects. setVisible gets a new reference, so Object.is fails and React re-renders.
  3. Render 2: identical DOM, no paint change, but the component function ran twice.

Now the user types b:

  1. Render 3: query is 'b', visible is still the full list. Two rows paint. Stale frame.
  2. Effect runs, setVisible([bob]), render 4 paints one row.

One keystroke, two renders, one painted frame showing the wrong rows. The derived version is one render per keystroke and never stale:

JSX
const visible = items.filter(i => i.name.includes(query));

The cost you now pay is that the filter runs on every render of SearchList, including parent re-renders where items and query didn't change. Memoise when you can show that matters:

JSX
const visible = useMemo(
  () => items.filter(i => i.name.includes(query)),
  [items, query]
);

useMemo is a performance hint, not a semantic guarantee: React is documented as free to discard cached values, and does in some offscreen and StrictMode paths. So it must never carry correctness. If the value must be right, compute it; if it must be cheap, memoise it.

Rough arithmetic for when it's worth it: a substring filter over 10k objects is about 0.5–2 ms on a current laptop, against a 16.7 ms frame budget at 60 Hz. 10k unmemoised is fine. At 1M rows the same filter is roughly 50–200 ms, and the fix is virtualisation or a worker, not useMemo alone. Measure with the React DevTools Profiler or performance.now around the call rather than guessing.

What belongs in state: query text, selected ids, open/closed UI flags, and server data (or a cache library's copy of it). What doesn't: filtered or sorted lists, counts, totals, isValid, formatted dates.

The one legitimate exception is state that must reset when a prop changes. Use key to remount the subtree, or the documented adjust-state-during-render pattern, compare the previous prop held in state and call setState during render, not an effect.

Failure modes and how they show up:

  • Stale frame. Two commits per interaction in the Profiler. Hidden in React Testing Library, because act() flushes effects before your assertions run, which is exactly why it survives casual testing.
  • Infinite loop. The effect sets state that appears in its own dependency array.
  • Memo that never hits. A dependency array containing an object or array literal rebuilt each render, so you pay for the memo and the computation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on refs for values that do not render, and what does not?

Answer

The 90-second answer. A runbook entry for a ref that holds a value the UI should be showing has four parts: the symptom as the user reports it, the one check that confirms the cause, the fix, and the test that proves the fix. It has no part that explains what a ref is. Target one screen, roughly 15 lines, because the reader has a symptom and a pager, not a tutorial budget.

Assumptions worth stating: the component already ships, the reader knows React, and the symptom is reproducible.

Belongs

ItemWhy it earns the line
Symptom, one line"The value on screen lags one input behind and only catches up when something unrelated re-renders."
Mechanism, one sentenceA ref write does not schedule a render, so a value read from a ref during render can be one render stale.
Confirming checkgrep -rn "react-hooks/exhaustive-deps" src/: a silenced dependency warning next to a useRef is the usual cause.
FixMove the value to state, or keep the ref and read it in an effect that depends on the input.
VerificationThe test that fails before the fix: type into the input, assert the rendered value changes with no other interaction.
Benign refsTimer handles, DOM nodes, previous-value trackers, "has mounted" flags: listed so on-call does not chase them.

Does not belong. The refs-vs-state explainer ("a ref is a mutable box that survives renders"): the reader already knows refs exist and needs to know which one is wrong. Trade-off essays on when refs are appropriate. Lint-policy debates. Anything that requires reading the whole component to understand the symptom: if the entry is longer than the component's render function, the check is buried.

The failure, traced.

JSX
function Search({ query }) {
  const queryRef = useRef(query);
  useEffect(() => { queryRef.current = query; }, [query]); // write after commit
  const normalized = queryRef.current.trim().toLowerCase(); // read during render
  return <Results query={normalized} />;
}

Mount with query = "a": the render reads queryRef.current, which useRef initialized to "a", so normalized is "a". Commit, then the effect runs and writes "a" again. Type "b": the render phase reads queryRef.current, still "a" (the effect that would write "b" runs after this render, not before it) so normalized is "a". Commit, the effect writes "b", and nothing schedules a render. The screen shows "a" until an unrelated state change re-renders, at which point it shows "b". One input behind, exactly as the symptom says.

Verification. One interaction: change the input, assert the output changed, no second click and no remount. If the assertion only passes after a second interaction, the value lives in a ref and this is the entry you are reading.

When the entry is wrong. If the value is read inside an event handler or an effect rather than during render, a ref is the correct tool and there is no bug: the entry should say so in one line so on-call stops. A ref read in a handler sees the latest write; a ref read during render sees the last committed write. That distinction is the whole entry.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Why does React require keys when rendering lists of elements, and what bugs or performance issues occur when keys are omitted or unstable?

Answer

What a strong candidate says first (60–120 seconds)

Keys give React a stable identity for each element among its siblings, so reconciliation can distinguish "the same item, moved" from "a different item". When you omit a key, React's fallback is the array index. The deciding criterion is whether the list's order or membership can change: if items can be inserted, removed, sorted or filtered, index keys alias identity to a slot and per-item state lands on the wrong row; if the list is static and never reordered, index keys are fine. React's own docs say so. Keys must be unique among siblings and stable across renders. They are scoped to the sibling list, not global, and React strips key before passing props, so a component never receives it.

Mechanism

React walks a parent's children and matches each incoming element to an existing fiber by (type, key). Three cases at a given position:

  1. Explicit key matches the previous fiber's key → fiber and its state are preserved, props updated.
  2. No key → React uses the index as the implicit key (0, 1, 2…).
  3. Key differs or type differs → old fiber unmounts (DOM removed, state discarded, cleanup effects run) and a new fiber mounts.

In development, a missing key logs Each child in a list should have a unique "key" prop. The snippets below are plain JSX; reconciliation by key is unchanged in React 18 and 19.

Failure mode 1: index keys when the list reorders

Prepending C to [A, B]:

IndexPrevious (key)Rendered (key)React actionState fate
0A (key=0)C (key=0)Match fiber 0, update props to CFiber kept: still holds A's local state
1B (key=1)A (key=1)Match fiber 1, update props to AFiber kept: still holds B's local state
2—B (key=2)Mount new fiberDefault state

If <TodoItem> owns uncontrolled state (a checkbox, a draft text input, an animation class, a useEffect cleanup) index 0 keeps A's checked box while rendering C's text. State visibly bleeds into the wrong record. Deletion and filtering shift every later index the same way. Memoization also breaks: with React.memo, every row after the insertion point gets new props, so all of them re-render instead of just the new one.

When index keys are safe

A list that is rendered once and never reordered, filtered, or spliced in the middle: a static legend, a fixed settings table, an append-only log where items only ever go on the end: is fine with index keys, and it avoids inventing IDs. The moment items can move or be removed from anywhere but the tail, switch to a stable ID.

Failure mode 2: unstable keys

key={Math.random()}, key={crypto.randomUUID()} computed during render, or key={JSON.stringify(item)} on a mutated object means no key ever matches across renders. React unmounts and remounts every sibling: DOM nodes are discarded and rebuilt, focus, text selection and scroll position are lost, cleanup effects run and child effects re-run each render. Reconciliation is O(N) either way; the difference is per-node work: unmount, mount, effect teardown and DOM creation versus a prop update.

Detection and the fix

Symptoms: focus jumping out of an input after a list update, checkboxes toggling the wrong row, CSS transitions restarting, useEffect cleanup logs firing on every render. React DevTools' "Highlight updates when components render" shows the whole list flashing. The fix is an ID that exists in the data: a database primary key, a server-assigned UUID. If the data has none, generate it once when the record is created (in the reducer, the fetch handler, or a useRef/WeakMap cache), never inside map. For a genuinely static list, keep the index and move on.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Under what specific conditions is using an array index as a key problematic in React, and when (if ever) is it acceptable?

Answer

Using an array index as a key becomes problematic whenever a list can change order, have items inserted or removed from anywhere other than the end, or contain components holding local state or uncontrolled DOM state (like <input> focus or text). It is acceptable only when the list is strictly static: items are never reordered, filtered, or mutated, and have no local state.

Mechanically, React reconciles siblings by pairing the key across consecutive renders. When you assign an index (key={0}, key={1}), React treats index 0 as the exact same component instance between renders, regardless of the underlying record's identity. If an item is prepended to the array, the new item occupies index 0, while the former item moves to index 1. React sees key={0} persisting, so it preserves the component instance, its internal useState, and uncontrolled DOM nodes at position 0, updating only the changed props. The UI visually renders the new item's props over the old item's internal state.

Consider prepending an item to a list of todo inputs:

JSX
// Bad: index as key on a dynamic list with uncontrolled state
{items.map((item, index) => (
  <TodoItem key={index} text={item.title} />
))}

function TodoItem({ text }) {
  const [checked, setChecked] = useState(false);
  return (
    <div>
      <input type="checkbox" checked={checked} onChange={e => setChecked(e.target.checked)} />
      <span>{text}</span>
    </div>
  );
}
ActionItem at index 0 beforeItem at index 0 afterComponent state React keeps at key="0"
User checks Todo ATodo A (checked: true)—checked: true
Prepend Todo BTodo ATodo B (receives props for B)checked: true (stale state attached to B!)

The failure mode is state corruption: Todo B renders on screen displaying Todo A's checked checkbox, while the last item in the list drops or gets desynchronized. Additionally, React fails to optimize DOM operations: rather than inserting a single DOM node at the top, React re-renders every item and overwrites DOM properties down the entire list.

When is it acceptable? Strictly when all three conditions from React's documentation hold: (1) the list and items are completely static (no reordering, insertion, or deletion), (2) items in the list have no IDs, and (3) the list is never reordered or filtered. Examples include a fixed pagination footer ([1, 2, 3, 4, 5]) or a static navigation bar where child items are purely functional, uncontrolled-state-free links.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How does React decide when to preserve or reset state across renders based on tree position and keys?

Answer

React ties state to a component's position in the UI tree, not to the component instance or function itself. When React renders, it compares the new element tree to the previous tree at the same structural position. If a component of the exact same component type (same function reference) sits at the exact same location in the tree hierarchy, React preserves its state. If the component type changes, or if the element moves to a different location in the tree hierarchy, React destroys the old subtree, unmounts it along with its state, and mounts a fresh instance.

Explicit keys override tree-position matching. Giving a component a key tells React to associate that component's identity with that key rather than its positional index among siblings. Changing the key of a component at the same tree position forces React to tear down the component and reset its state, while keeping the key stable allows React to preserve state even if the element's sibling position shifts.

Structural Matching vs. Keys

JSX
// Scenario 1: Preserves state across condition changes
// Both branches render <Counter /> at root -> same position, same type.
{isFancy ? <Counter isFancy={true} /> : <Counter isFancy={false} />}

// Scenario 2: Resets state because position in tree changes
// Left branch is inside a <div>; right branch is inside a <section>.
{isFancy ? (
  <div><Counter /></div>
) : (
  <section><Counter /></section>
)}

// Scenario 3: Explicit key forces reset at identical tree position
// Same type and position, but changing userId destroys and recreates Profile
<Profile key={userId} userId={userId} />

The Internal Mechanism

During the render phase, React reconciles children by traversing fiber nodes. For a given position:

  1. Type and Key Match: If prevChild.key === nextChild.key and prevChild.type === nextChild.type, React reuses the existing fiber node. The fiber's memoizedState (the linked list of hooks) is retained, and only new props are applied.
  2. Type or Key Mismatch: If prevChild.type !== nextChild.type or prevChild.key !== nextChild.key, React marks the old fiber for deletion (to be unmounted during commit) and creates a brand-new fiber with empty hook state (memoizedState = null).
CaseOld Fiber at SlotNew Element at SlotOutcome
Same type, same/no key<Editor key="a" /><Editor key="a" />State preserved; props updated
Different type<Editor /><Viewer />Old state deleted; <Viewer> mounts fresh
Different key, same type<Editor key="user-1" /><Editor key="user-2" />Old state deleted; <Editor> mounts fresh
Wrapped parent tag<Editor /><div><Editor /></div>Old state deleted; tree path changed

Production Failure Modes

  • Accidental State Leakage: Switching between two entities (e.g., editing Comment A then Comment B) using the same component <CommentEditor /> at the same tree position without passing a key={comment.id}. The draft text, dirty flags, or unsaved local state from Comment A persist into Comment B.
  • Nested Component Declarations: Defining a component function inside another component's render body (function Parent() { function Child() { ... } return <Child />; }). On every render of Parent, Child gets a brand new function reference (prev.type !== next.type), causing React to unmount and remount Child on every tick, destroying DOM nodes, focus, and state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

What is the primary purpose of useEffect, and when does its cleanup function execute relative to component lifecycle and re-renders?

Answer

The primary purpose of useEffect is synchronization with an external system: anything outside React's declarative state model, such as DOM APIs, browser timers, network connections, or third-party widgets. It is explicitly not a lifecycle hook or a trigger to compute React state.

Cleanup Execution Timing

React defers useEffect until after the browser paints the updated DOM. Its cleanup function executes at two specific times:

  1. Before the effect re-runs on a re-render: If dependencies change, React runs the previous render's cleanup function using the props and state captured in that previous render snapshot, right before executing the new effect.
  2. On unmount: When the component is removed from the DOM, React executes the cleanup function from the final rendered commit.

Crucially, cleanup on re-render does not fire during render or during the commit phase; it fires asynchronously after commit and paint, immediately preceding the new effect invocation.

Execution Trace Across Re-renders

Consider a chat connection keyed by roomId changing from 'general' to 'travel':

JSX
useEffect(() => {
  const connection = createConnection(roomId);
  connection.connect();

  return () => {
    connection.disconnect();
  };
}, [roomId]);
PhaseActionCaptured roomIdNotes
1. Initial RenderRender & Commit <Chat roomId="general" />"general"DOM painted
2. Post-paintEffect runs: createConnection("general").connect()"general"Connection established
3. Prop changeRe-render <Chat roomId="travel" />"travel"DOM painted
4. Post-paintCleanup runs: disconnect()"general"Cleans up previous snapshot
5. Post-paintEffect runs: createConnection("travel").connect()"travel"New connection established
6. UnmountCleanup runs: disconnect()"travel"Cleans up final active connection

Failure Modes

  • Omitted Cleanup / Stale Subscriptions: Omitting the cleanup creates dangling listeners or duplicate connections. When roomId changes 5 times, failing to disconnect leaves 5 active sockets consuming memory and processing redundant events.
  • Race Conditions with Async Code: If the effect fetches data without cleanup or an abort flag (AbortController), an earlier slow request can resolve after a newer fast request, overwriting fresh UI state with stale data.
  • State Synchronization Traps: Using an effect to calculate derived state from props causes an extra unnecessary render pass (Render 1 -> Commit -> Effect -> setState -> Render 2). This calculation belongs directly in the render function.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Why do stale closures occur inside useEffect, and how does the dependency array prevent them?

Answer

Stale closures in useEffect occur because JavaScript functions close over variable bindings within their lexical scope at the exact moment of execution. In React, each render is an isolated execution with its own immutable snapshot of props and state. If an effect function is not recreated across renders, it retains a reference to the variables from the specific render pass in which it was instantiated.

Mechanically, when React runs a component function, local identifiers like count or userId are constants bound to that specific invocation. When you pass a callback to useEffect, that function captures those local variables via its closure. If you provide an empty dependency array [] (or omit changed values), React caches that callback on the fiber node and skips re-running or rebinding it on subsequent renders. As a result, long-lived subscriptions, intervals, or event handlers invoked later will read the captured snapshot from render 1 rather than the latest state.

JSX
function Counter() {
  const [count, setCount] = useState(0);

  // Stale closure: interval callback captures `count = 0` forever
  useEffect(() => {
    const id = setInterval(() => {
      console.log(count); // prints 0 on every tick
      setCount(count + 1); // 0 + 1: state freezes at 1
    }, 1000);
    return () => clearInterval(id);
  }, []); // React never resubscribes

  // Correct: dependency array forces tear-down and resynchronization
  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1); // avoids capturing count entirely
    }, 1000);
    return () => clearInterval(id);
  }, []); // safe because setCount updater is stable
}

The dependency array prevents stale closures through synchronization, not memoization:

  1. Object.is Comparison: After commit, React iterates through the dependency array comparing each element to its value from the prior render using Object.is(dep[i], prevDep[i]).
  2. Tear-Down and Re-Execution: If any dependency differs, React immediately invokes the previous cleanup callback (releasing old timers, sockets, or listeners) and executes the newly defined effect callback from the current render snapshot.
  3. Fresh Lexical Scope: The new effect instance closes over the variables of the latest render pass, ensuring any newly registered callback accesses current values.
MechanismStale Closure TriggerResolution
State UpdatesetCount(count + 1) in []Use updater function: setCount(c => c + 1)
Subscription / SocketReading roomId in [] socket listenerAdd [roomId] to dependencies and return disconnect in cleanup
Non-state VariableReading changing external mutable refRead via ref.current directly inside callback (bypasses closures)

A critical failure mode occurs when engineers lie to the dependency array (e.g., using eslint-disable-next-line react-hooks/exhaustive-deps) to suppress infinite re-render loops. Suppressing the linter fixes the loop symptom but leaves the closure frozen on the initial render snapshot. If an effect depends on changing state, the proper architectural fix is either declaring the dependency and writing a resilient cleanup routine, extracting the calculation out of the effect into an event handler or derived value, or using a functional state updater.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain the effects you do not need without using the usual slogan?

Answer

What I'd say first

Assume function components with hooks (React 18/19) and a codebase where effects have piled up. An effect you don't need is one whose only job is to keep React state in sync with other React state or props. Render already recomputes on every state change, so that effect is a second pass over work React was going to do anyway. Three shapes cover most of them: a value computed from props or state, state that should reset when a prop changes, and logic that should run because the user did something.

Why it's a second pass

Effects run after the commit, not during render. So useEffect(() => setX(...), [y]) computes nothing render couldn't: it commits, then schedules another render to apply the state it just set. That's the cost: one extra commit per effect that sets state, and the ordering between them is only visible if you read every effect in the tree.

A trace

JSX
function Checkout({ country, price, qty }) {
  const [city, setCity] = useState(null);
  const [area, setArea] = useState(null);
  const [total, setTotal] = useState(0);

  useEffect(() => setCity(null), [country]);
  useEffect(() => setArea(null), [city]);
  useEffect(() => setTotal(price * qty), [price, qty]);
}

One user action: picking a new country while city and area are already set:

  • Render 1: country changes. Commit. Effect 1 fires, setCity(null).
  • Render 2: city is null. Commit. Effect 2 fires, setArea(null).
  • Render 3: area is null. Commit. Nothing depends on area, so it stops.

Three renders for one click. The total effect doesn't fire here because price and qty didn't change: it's the derived-value case, a separate extra commit whenever they do. The version without the effects:

JSX
function Checkout({ country, price, qty }) {
  const total = price * qty;          // derived during render
  return <Address key={country} />;   // key resets city/area
}

Render 1: country changes, the key remounts Address with fresh state, total is computed inline. One render.

Failure modes

The cascade is the one to name. Each effect's setState feeds the next effect's dependency, so the number of renders equals the length of the chain, and no single file shows the order. It passes casual testing because the happy path often sets the same value twice: setCity(null) when city is already null bails out of the re-render, so the cascade only appears when the intermediate state actually differs. That's why it survives review: the bug needs a specific starting state.

Second: an effect that mirrors a prop into state goes stale the moment the prop changes without the effect's dependency list noticing.

When you do need one

Keep effects for things outside React: a WebSocket subscription, a DOM measurement, a timer, an analytics call. The test is what the effect touches, if it only touches props, state, or other components, it belongs in render or in the handler that caused it.

The conditional part

Semantics first: if the derived value and the effect-set value can ever differ, fix that before counting renders. Once they're equivalent, the cost is commits, and you measure it: the React DevTools Profiler shows commit count per interaction. I wouldn't quote a number without that measurement.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of cleanup and out-of-order responses?

Answer

I'd refuse a design on this axis in three cases, and only three.

Assumptions: React 18, effects re-run when a dependency changes, and the network gives no ordering guarantee. Two requests fired in order can resolve in either order. StrictMode's double-invoke in development is a detector, not a defect; I don't refuse for it.

1. An effect starts async work and writes state from the response, but returns no cleanup. This is the common one. The effect re-runs on a dependency change while the previous request is still in flight, and the older response lands last and wins.

2. Cleanup exists but only discards, while the design claims cancellation. A boolean flag stops the stale setState; it does not stop the request. If the design's stated goal is to cut server load or mobile data, a flag-only cleanup doesn't meet it: refuse and require AbortController.

3. A subscription's teardown is wired to unmount only. WebSocket, setInterval, addEventListener, ResizeObserver, if the design unsubscribes on unmount but not on dependency change, you leak one subscription per change.

Trace for case 1. User types ab, then abc 100 ms later. ab resolves at 400 ms, abc at 180 ms.

JSX
useEffect(() => {
  let active = true;
  fetchResults(query).then(r => { if (active) setResults(r); });
  return () => { active = false; };
}, [query]);

Step by step: query ab → effect runs, active₁ = true, request A starts. At t=100 ms query becomes abc → React runs the previous cleanup, active₁ = false, then the new effect sets active₂ = true and starts request B. At t=180 ms B resolves; active₂ is true, so setResults("abc"). At t=400 ms A resolves; active₁ is false, so it's discarded. Remove the cleanup and A's setResults("ab") runs at 400 ms, overwriting the newer result: the UI shows results for ab while the box reads abc.

DesignRefuse?Why
Effect fetches, no cleanupYesStale response overwrites newer
Flag cleanup, goal is cancellationYesRequest still in flight; load not cut
AbortController in cleanupNoBoth discards and cancels
Subscription torn down on unmount onlyYesLeaks one per dependency change
Fetch in a library data layer (React Query, SWR)NoKeyed cache discards superseded responses

Detection: the bug hides on fast networks and short inputs, because the stale response usually arrives before the next keystroke. Reproduce by throttling to Slow 3G and typing during the in-flight window, or by adding an artificial delay to the first request. A test that types ab, waits, then types abc and asserts the final render is abc catches it deterministically.

What I would not refuse: a design that fetches in an effect with a correct cleanup, or one that delegates to a keyed data layer. The refusal is about the missing invalidation path, not about fetching in effects as such.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of strictMode double invocation in development?

Answer

Inject an effect that acquires a resource and never releases it: a WebSocket opened in useEffect with no cleanup. It is the cleanest probe because it is silent on the happy path (the UI renders fine, the message sends fine) and only the resource count betrays it.

JSX
useEffect(() => {
  const ws = new WebSocket(`wss://chat/${roomId}`);
  console.log('open', roomId);
  return () => { ws.close(); console.log('close', roomId); };
}, [roomId]);

Delete the return line and mount once in a development StrictMode build with a stable roomId. The console shows:

open room-7
close room-7
open room-7

Two setups, one cleanup between them, one live socket left over. The same component in a production build logs open room-7 once. A team that understands double invocation reads the dev trace as "my cleanup is missing" and fixes the effect; a team that memorised the slogan reads it as "React is being weird in dev" and reaches for StrictMode's off switch.

Vary the injection to separate the levels of understanding:

Injected failureDev StrictMode traceProduction symptom it predicts
No cleanup at all2 open, 0 closeold socket stays open on every roomId change
Cleanup closes a stale handle (captured from a ref, or the wrong timer id)2 open, 1 closeleak appears only on the second change
Render pushes to a module-level cachecache grows by 2 per mountcache grows by 1 per mount, unbounded
fetch with no AbortController2 in-flight requestsa stale response lands last and overwrites fresh state

The second row is the one that catches people who think "I have a cleanup, so I'm fine." The cleanup has to reverse the specific setup that ran, not just run.

The tell that the team does not understand it is the fix they reach for. A useRef guard, if (ref.current) return; ref.current = true;, suppresses the second setup in dev and looks like a pass, but it also suppresses the legitimate re-run when roomId actually changes, so the socket never reconnects. Turning StrictMode off is the same mistake with less code: the effect still runs twice in production the first time a dependency changes, and now nothing warned you.

Detection is counting, not reading. Assert on the resource, not the render: server-side connection count per room, ws.readyState on the instance you thought you closed, request count in the network panel, or a cache-size assertion in a test. If the count is 2 in dev and 1 in prod for the same mount, the effect is impure and the cleanup is incomplete: that is the whole lesson, and the injected failure is what makes the team say it out loud.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names useLayoutEffect against useEffect as the cause?

Answer

First 60 seconds. An alert that names useLayoutEffect as its cause has already done your diagnosis for you, and that is the problem. Alerts fire on symptoms: INP, long tasks, layout shift, error rate. A hook name in the alert body is a hypothesis someone encoded, usually a lint rule or a static-analysis job, not a measurement. On-call's first move is to ask what the alert actually measures. If the answer is "a rule matched in the diff," it is a ticket for the owning team, not a page. If it correlates with a user-facing metric, the hook is a plausible contributor and you confirm it before touching code.

Triage table.

What the alert isSeverityOn-call action
Static rule / lint finding, no user metricP4 ticketRoute to owning team, no page
p75 INP > 500 ms on the route, hook named as suspectP2Confirm with a trace, then mitigate
CLS regression on a tooltip or popoverP3Check the measure-then-adjust path
SSR warning about useLayoutEffectP4Check for a server-rendered path

Why the hypothesis is plausible at all. useLayoutEffect runs synchronously after React commits DOM mutations and before the browser paints. Its body sits inside the frame budget: 16.7 ms at 60 Hz, 8.3 ms at 120 Hz. A 40 ms layout effect is two dropped frames, and it surfaces as a long task, which is exactly what an INP alert sees. useEffect runs after paint, so the same work lands outside the frame, but it can still cause jank if it sets state and triggers another render.

Confirming it. Pull a performance trace of the route and look at the commit. React DevTools Profiler shows commit duration; a layout effect that dominates it is your suspect.

JSX
// Suspect: measurement plus a request in the same layout effect
useLayoutEffect(() => {
  const { height } = ref.current.getBoundingClientRect();
  setTop(anchorTop - height);
  fetch('/api/telemetry'); // this is the long task
}, [anchorTop]);

The fix is to move the non-measurement work out, not to swap the hook:

JSX
useLayoutEffect(() => {
  const { height } = ref.current.getBoundingClientRect();
  setTop(anchorTop - height);
}, [anchorTop]);

useEffect(() => {
  fetch('/api/telemetry');
}, []);

Failure modes. Paging on a lint rule burns the rotation and trains people to ignore the alert. Swapping useLayoutEffect for useEffect to clear the alert trades a long task for a visible flicker: the element paints at the wrong position for one frame, then jumps. That is a real regression the alert will not catch. And if the component renders on the server, useLayoutEffect warns because there is no layout to measure: moving it to useEffect does not fix that either; the measurement has to be gated on the client.

What to do. Treat the named cause as a lead. Confirm the symptom is user-visible, confirm the hook is in the hot path with a trace, then fix the effect body rather than the hook choice. If there is no user-facing metric behind the alert, downgrade it and fix the alert's routing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you review a pull request whose risk is useMemo and useCallback as a measured trade?

Answer

In the first minute: I'd ask what each memo is buying and how it was measured. Two questions decide the review: does the memo change an identity something downstream compares, and is the computation it skips measurably expensive? If neither holds, it is cost without benefit and I'd ask for it to come out.

Correctness before performance. A dependency array is a correctness surface, not a perf knob: a missing dep is a stale closure, and react-hooks/exhaustive-deps firing is a bug report, not noise to suppress. React's docs are explicit that useMemo is a performance optimisation and not a semantic guarantee (React may discard a cached value, with off-screen content given as the example) so the calculation must stay correct if it runs again. Anything that must survive belongs in state or a ref, not in a memo.

Then the mechanism, because it decides which memos are real. useCallback(fn, deps) is useMemo(() => fn, deps); both compare each dep with Object.is and return the cached value when all match.

JSX
const Row = React.memo(function Row({ row, onSelect }) {
  return <li onClick={() => onSelect(row.id)}>{row.name}</li>;
});

function Table({ rows, pick }) {
  const sorted = useMemo(() => [...rows].sort(byName), [rows]);
  const onSelect = useCallback((id) => pick(id), [pick]);
  return <ul>{sorted.map(r => <Row key={r.id} row={r} onSelect={onSelect} />)}</ul>;
}

Trace a parent re-render where rows and pick keep their references: useMemo compares one dep, finds it equal, returns the cached array. The 10,000-row sort does not run. useCallback returns the same function reference. React.memo's shallow compare on Row sees the same row and the same onSelect, so all 10,000 rows bail out. Now change one thing: define pick inline in the parent. Its identity changes every render, useCallback returns a new function, the shallow compare fails, and every row re-renders. The memo still pays its cost and delivers nothing: the classic shape of this PR.

That asymmetry is the argument. A 10,000-row sort lands in the low milliseconds; a one-element Object.is compare is nanoseconds. Three to six orders of magnitude. The memo earns its keep when the skipped work is on the millisecond side and the dep is stable; it is pure overhead when the skipped work is an add or a template literal.

MemoWhat it actually buysCall
useMemo(() => [...rows].sort(byName), [rows]), stable rowsskips a multi-ms sortkeep
useMemo(() => ${first} ${last}, [first, last])skips a string concatdrop
useCallback on a prop to a React.memo childskips the child's re-renderkeep
useCallback on a prop to a plain childnothing: the child re-renders anywaydrop
useMemo for a context value objectskips re-rendering every consumerkeep

Failure modes I'd name in the review, with how each shows up:

  • Unstable dep defeats the memo silently. An inline object, array or function in the dep list, or a parent passing rows={data.filter(...)}. The profile shows the cost and none of the benefit. Detect by counting executions of the memo body, or by reading the React DevTools Profiler's "why did this render".
  • Memo on a value consumed only inside the same component. The component re-renders regardless, so only the computation is saved. If that computation is cheap, nothing is saved.
  • Stale closure from a suppressed dep. Wrong data, not slow data. This is the one that ships.
  • Memo standing in for a structural fix. If the list is slow because it renders 10,000 rows, windowing or pagination beats memoising each row.

What I'd write in the PR: keep the memos whose skipped work is measurable and whose deps are stable, delete the rest, and ask for the profile that motivated the change plus a comment naming the measurement. If the repo has React Compiler enabled, hand-written useMemo and useCallback are largely redundant, the compiler memoises automatically, and the review shifts to whether the compiler bailed out on that component.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does memo and the identity of props force that a junior answer usually skips?

Answer

React.memo compares prop identity, not prop value. So it doesn't just skip renders: it forces every call site to keep prop references stable, and it charges a comparison on every parent render whether or not the bailout fires. A junior answer stops at "wrap it in memo to skip re-renders" and misses that the cost and the constraint land on the caller.

Mechanism: memo shallow-compares previous and next props with Object.is per key. All keys equal → bail out of rendering that component. Any key different → render as normal. The bailout is decided by the caller, not the component.

JSX
const Row = memo(function Row({ item, onPick }) {
  return <li onClick={() => onPick(item.id)}>{item.label}</li>;
});

function List({ items, onPick }) {
  return (
    <ul>
      {items.map((item) => (
        <Row key={item.id} item={{ ...item }} onPick={() => onPick(item.id)} />
      ))}
    </ul>
  );
}

Trace one parent render of List with 3 items. Each row allocates a new object for { ...item } and a new function for () => onPick(item.id). memo compares item: Object.is(prevItem, nextItem) is false, and the shallow compare returns on the first unequal key, so Row re-renders. Three rows, three failed comparisons, three renders: the same work as no memo, plus three shallow compares.

Fix the call site instead:

JSX
<Row key={item.id} item={item} onPick={onPick} />

Now item is the same reference the array holds, and onPick is stable if the parent defines it with useCallback. Object.is returns true for both keys and memo skips the render.

That fix is where the trade-off bites. onPick is only stable while its useCallback deps don't change. The moment it closes over something that changes (a filter, a selected id, a counter) its identity changes and memo fails again. Freezing the deps to keep identity stable gives you a stale closure instead. memo trades render cost for identity bookkeeping maintained at every call site, and that bookkeeping breaks silently.

Two more places it breaks:

  • Context. memo compares props only. A memoised component that reads a context value re-renders when that context changes, whatever its props do.
  • children. If the parent re-renders, the element passed as children is a new object, so memo fails. It only helps when the element is created by a component that doesn't re-render.

When not to use it: components that are cheap to render, components whose props are inherently fresh (a new object per render is the API), and components that read context. The comparison itself is cheap, 4 props is 4 Object.is calls, but it is paid on every parent render, and if the bailout never fires it is pure overhead that shows up in a profile as memoised components rendering anyway.

Measure before and after with the React DevTools Profiler: record an interaction, then check the render count and commit duration for the memoised subtree. If the count doesn't drop, delete the memo.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you brief product on why context and who re-renders delays a ship date?

Answer

The briefing, in one breath: "The checkout page has a re-render bug we can fix in three days or ship around in one. Shipping around it means the promo-code field drops keystrokes on mid-range Android; fixing it moves the release from the 14th to the 17th. I recommend the three days."

Everything after that is what product asks next.

Why it's slow, in their terms. React re-renders a component when its parent re-renders, or when a value it subscribes to changes. Context is a subscription: every component under a provider re-renders whenever the provider's value changes identity. Identity, not content: a fresh object literal is a new identity even when the fields inside are identical.

JSX
// every parent render builds a new object -> all consumers re-render
<AppCtx.Provider value={{ user, filters }}>

// stable identity until user or filters actually change
const value = useMemo(() => ({ user, filters }), [user, filters]);
<AppCtx.Provider value={value}>

Trace it: the promo-code input keeps its text in AppCtx. Each keystroke calls setState on the provider's parent. The parent re-renders, builds a new { user, filters } literal, and all 40 consumers under it re-render: including the 200-row results table, which reads neither user nor the promo code. On a mid-range Android that commit runs ~180 ms; typing at 8 characters/second, the input never catches up. Split the promo code into its own provider and only the 2 components that read it re-render: same keystroke, ~12 ms. (Profiler figures from a representative device: illustrative, re-measure on the target.)

The trade-off, as a table product can read:

OptionCostRisk
Ship as-is0 daysdropped keystrokes on a slice of sessions; support load; likely hotfix later at higher cost
Memoise the value, split the context3 daystouches checkout; the flow needs re-testing
Move promo state to a store with selectors5 daysnew dependency, larger review

When they push back. "It's just a text field": the field is fine; it's wired to the whole page. "Can't we memo the components?": React.memo on a consumer only helps if its props are stable; the context value identity still changes, so the subscription still fires. "Ship it and hotfix": the hotfix costs the same three days plus an incident and a rollback path, and the bug is worst under load, which is when you least want it.

How we know it's real, not theoretical. React DevTools Profiler, "highlight updates" on the checkout route: type one character and count the components that flash. Whole tree means the diagnosis holds; two means I'm wrong and I'll say so.

What I need from product. A decision on the date, and whether the promo field can be feature-flagged off for the first release: that buys the three days without moving the date.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about controlled against uncontrolled inputs?

Answer

The belief under test. My default is: a controlled input costs a React render per keystroke, so a form with enough fields should go uncontrolled or read from FormData on submit. That is the only claim that actually decides the choice for most teams: the correctness differences (uncontrolled state lives in the DOM node, so it resets on remount and can't drive derived UI) are known and not in dispute. So the experiment has to attack the performance claim, not the semantics.

The experiment. One file, one prop for field count, one toggle for mode, one measurement: keystroke to next paint.

JSX
function Harness({ controlled, fields }) {
  const [values, setValues] = useState(() => Array(fields).fill(''));
  const out = useRef(null);

  const measure = () => {
    const t0 = performance.now();
    requestAnimationFrame(() => requestAnimationFrame(() => {
      out.current.textContent = (performance.now() - t0).toFixed(1) + ' ms';
    }));
  };

  return (
    <>
      {Array.from({ length: fields }, (_, i) =>
        controlled ? (
          <input key={i} value={values[i]} onKeyDown={measure}
                 onChange={(e) => setValues(v => v.map((x, j) => j === i ? e.target.value : x))} />
        ) : (
          <input key={i} defaultValue="" onKeyDown={measure} />
        )
      )}
      <output ref={out} />
    </>
  );
}

Run it at 1, 10, 100 and 1000 fields, production build, no StrictMode, on the slowest device you ship to. Type into the last field and read the number.

The decision rule. The frame budget is 16 ms. Illustrative numbers from a mid-range laptop:

fieldscontrolleduncontrolled
1~2 ms~2 ms
10~4 ms~2 ms
100~18 ms~3 ms
1000~140 ms~4 ms

If your real forms sit at 10–20 fields and controlled lands at ~4 ms, the performance argument for uncontrolled is dead: I would switch to controlled everywhere and take the correctness guarantees for free. If you are at 100+ fields and controlled crosses 16 ms, uncontrolled (or FormData on submit) earns its place. That is the mind-change: a number, not a preference.

Why the measurement is easy to get wrong. Double-rAF approximates keystroke-to-paint; it does not capture the browser's own input latency, so treat it as a relative comparison, not an absolute. StrictMode double-invokes renders in dev and roughly doubles the controlled figure: measure a production build. React 18 batches the onChange setState into one commit, so the cost scales with the number of fields re-rendered, not the number of keystrokes. And the profiler's commit time excludes layout and paint, so it understates the controlled cost; the rAF delta includes them.

The smaller experiment, if you want it. Five lines: mount an uncontrolled input, type into it, then change its key to force a remount. The value resets. That proves uncontrolled state lives in the DOM node, but nobody disputes it, so it will not change your mind about anything.

What the outcome does not decide. A slow controlled form does not force uncontrolled. You can keep controlled semantics and cut the cost: memoize the field list so only the edited field re-renders, or use a library that keeps values in refs and re-renders on demand. The experiment tells you whether you need to pay for that at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

How does hooks and the order they are called in interact with rollback, and where do people ignore that?

Answer

Assumptions: React 18/19 function components, a development build with StrictMode on where I show dev-only output, production behaviour noted where it differs.

The first minute. "Rollback" hides two separate facts, and the hook rule only makes sense once they are split apart. React's render phase is provisional: hook state is built on a work-in-progress fiber and becomes the component's real state only at commit. Discard that render: a setState called during render, a suspension, an interrupted concurrent render, an error caught by a boundary, StrictMode's dev re-render, and the whole hook list goes with the tree. There is no per-hook rollback and none is needed. Hook identity is positional: each hook call takes the next node from the list left by the last render React kept, and a discarded render does not reset that baseline. The second fact is the one people skip: discarding a render does not undo anything a hook wrote outside the fiber while it ran. A socket opened in an initializer, a ref written in the render body, a module counter bumped inside a memo factory.

The list, and the single thing React checks. React compares how many hooks this render called against the previous list. More hooks than before throws "Rendered more hooks than during the previous render" rather than reading off the end. That check is arity only, so two branches with the same number of hooks slip past it silently:

JSX
function Panel({ editing }) {
  if (editing) {
    const [draft, setDraft] = useState("");     // slot 1
    const [dirty, setDirty] = useState(false);  // slot 2
    return <Editor value={draft} dirty={dirty} onChange={setDraft} onDirty={setDirty} />;
  }
  const [rows, setRows] = useState([]);          // slot 1
  const [page, setPage] = useState(0);           // slot 2
  return <Table rows={rows} page={page} onRows={setRows} onPage={setPage} />;
}

Mount with editing === false: slot 1 is [], slot 2 is 0. Flip to editing: draft is that array and dirty is 0, because those are the values sitting in slots 1 and 2. Type three characters, slot 1 becomes "abc", then flip back: rows === "abc", so rows.map(...) throws TypeError, or a rows.length guard renders 3 phantom rows for content that was never a list. React never complained.

What a rollback discards, and what it doesn't.

TriggerDiscardedSurvives
setState during renderthat render's output; React re-renders immediatelythe queued update, so the retry already sees the new state
Suspense retry / interrupted concurrent renderthe partial work-in-progress treecommitted state and queued updates; every render-body write
Error caught by a boundarythe failed render, then the tree below unmountsanything the failed render wrote to refs, modules, the network
StrictMode dev re-renderone of the two passeswrites made by either pass

React's hook implementation caps the immediate re-render case at 25 consecutive passes, then throws "Too many re-renders".

The initializer trace. Development build, one mount inside StrictMode:

JSX
let opened = 0;

function Live({ url }) {
  const [socket] = useState(() => {
    opened += 1;
    console.log("opening socket", opened);
    return new WebSocket(url);
  });
  return <span>{socket.readyState}</span>;
}
// opening socket 1
// opening socket 2

opened === 2, two sockets are open, and React keeps one as the hook value while the other's only reference is thrown away, so nothing will ever close it. The react.dev useState reference says the initializer may be called twice under StrictMode and that the result of one call is ignored: the side effect is not. The production analogue is a mount that suspends and retries: the fiber was never committed, so the initializer runs again from the top.

Where people ignore this.

  • A double fetch or duplicate subscription seen in dev and written off as a StrictMode quirk. Same code re-runs on a Suspense retry or an interrupted transition in production.
  • if (!ref.current) ref.current = build() as a run-once guard in the render body. useRef returns the same object across renders, so the write survives a render that does not. The docs ban reading or writing ref.current during render except for initialization.
  • Treating useMemo as a cache with a guaranteed hit, and depending on it for correctness. It is a performance optimisation; React may discard the value and recompute.
  • Reducers and updater functions held to exactly-once. They can be replayed in dev and recomputed on a retry, so they must be pure given their inputs.
  • Expecting an error boundary to hand back a clean instance. Without a changed key the component keeps the last committed state, not the failed render's. Only a remount resets every slot, and it also resets everything you wanted to keep.

The test that separates safe from broken here is replay: run the mount twice in dev, check for duplicate log lines, sockets or requests, and make the effect that owns the resource close it in cleanup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites error boundaries and Suspense boundaries but cannot apply it?

Answer

Skip the vocabulary round. A candidate who can recite both mechanisms has already passed the definitions question, so I hand them a file and ask about behaviour instead. First question: the API returns 500. What is on screen, and which component decided that?

JSX
// React 18.3 + createRoot. wrap() is the contract Suspense-aware libraries
// (Relay, SWR, React Query in suspense mode) implement internally.
function wrap(promise) {
  let status = 'pending', result;
  const suspender = promise.then(
    v => { status = 'success'; result = v; },
    e => { status = 'error';   result = e; }
  );
  return () => {
    if (status === 'pending') throw suspender;
    if (status === 'error')   throw result;
    return result;
  };
}

const readUser = wrap(
  fetch('/api/users/7').then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
);

function Profile() {
  const user = readUser();
  return <h1>{user.name}</h1>;
}

export default function App() {
  return (
    <ErrorBoundary fallback={<Failed />}>
      <Suspense fallback={<Skeleton />}>
        <Profile />
      </Suspense>
    </ErrorBoundary>
  );
}

Probe 1: trace the 500. Expected: Failed, and only Failed. While the request is in flight, readUser throws the suspender and Suspense paints Skeleton. When the fetch settles as a rejection, the closure flips status to 'error', React re-renders Profile, and readUser throws Error('HTTP 500'). A thrown value is not a suspension: the Suspense boundary above has nothing of its own to catch, so the error keeps moving up to ErrorBoundary, whose getDerivedStateFromError returns {hasError: true} and mounts Failed in place of its entire subtree. An answer of "the skeleton keeps spinning" or "Suspense shows an error state" means the vocabulary is there and the model is not.

Probe 2: Failed gets a Retry button that re-renders App. What happens? Expected: nothing. Two pieces of state are stuck: the boundary's hasError, and status === 'error' inside the closure. Reset only the boundary and Profile renders again, readUser() throws the same cached error, the boundary catches it and Failed comes back, often within the same tick, which is why it reads as a dead button. Reset only the resource and the boundary still holds hasError true, so Failed never unmounts. The fix clears both: drop the cached entry (or key the resource on an attempt counter) and remount the boundary, for example key={attempt} on ErrorBoundary. This is the probe that separates someone who has wired Suspense up from someone who has only read about it.

Probe 3: add a Refresh button inside Profile whose onClick calls the same fetch and drops the rejection on the floor. Where does that error land? Expected: nowhere in the tree. Boundaries catch errors thrown during render, from a lifecycle, or synchronously out of an effect body; they never see a rejected promise inside an event handler, a timer, or a .then: that surfaces as an unhandled rejection in the console and nothing else. A candidate who reaches for a boundary here is applying the slogan.

Probe 4: what one change keeps the page header alive when Profile fails? Expected: move the boundary down to wrap only Profile, because a boundary swaps out its whole subtree, header included.

Pass is when they name the boundary that owns each failure and can make Retry work without me pointing at the bug.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document server components against client components so the next owner can operate it?

Answer

The 90-second answer

Document the boundary as a contract with four parts, not as a description of how React works: a comment at every "use client" site saying why that file is client; a boundary map. A checked-in table of client entry points and what each pulls in; an enforcement layer that fails the build on violations; and a bundle budget in CI. The next owner's real question is "if I add a hook here, what breaks, and how do I find out?" The documentation should answer that without them reading the whole import graph.

What actually needs documenting

Two rules carry all the operational weight. First, "use client" is transitive downward: every module imported by a client file joins the client graph, so the directive's position determines the bundle. Second, props crossing the boundary must be serializable: React's RSC payload handles primitives, Date, Map, Set, BigInt, TypedArrays, Promises, JSX elements and Server Actions; it rejects class instances and ordinary functions. Both are invisible in a diff, which is why they belong in a comment and a lint rule rather than a wiki page nobody opens.

WhatWhere it livesHow it's enforced
Why this file is clientComment above "use client"Code review
Server-only modulesimport 'server-only' at the top of the moduleBuild error if it reaches a client bundle
Client entry pointsboundaries.md: file, reason, importsReviewed when the table changes
Bundle costCI step comparing route sizesFails the build over budget
TSX
// app/dashboard/page.tsx — Server Component (no directive)
import 'server-only';            // build fails if this file ever joins the client graph
import { db } from '@/lib/db';   // never reaches the browser
import { Toggle } from './toggle';

export default async function Page() {
  const rows = await db.recent();          // stays on the server
  return <Toggle initial={rows.length} />; // number: serializable
}
TSX
// app/dashboard/toggle.tsx
'use client';
// Client because: useState + onClick. Imports only react. Do not import @/lib/db here —
// it would pull the whole data layer into the client bundle.
import { useState } from 'react';
export function Toggle({ initial }: { initial: number }) { /* ... */ }

Making the cost visible

next build prints First Load JS per route. Set the budget from the current number, not a guess: if /dashboard reports 92 kB and the client leaf is 4 kB, a 40 kB date-formatting library added to toggle.tsx shows up as 132 kB on the next build. That delta is the alarm; the absolute number is noise.

Failure modes

  • A hook added to a page file silently moves that page's whole import graph client-side. Detected by the CI size delta, not by tests: the happy path renders identically.
  • A secret imported into a client file ships to the browser. server-only turns that into a build error; without it, nothing catches it.
  • next/dynamic with ssr: false is rejected inside a Server Component in Next.js 14+; the fix is to move the dynamic import into a client file, which is exactly the kind of thing the boundary map should record.

Trade-offs

Pushing the boundary to the smallest leaf minimizes the bundle but multiplies the number of client entry points and serialization hops. A page-level boundary is simpler to document and review, and is the right call when the page is interactive throughout or the server data is small. Push down when a large server-only dependency sits next to a small control; stop when the extra entry points cost more review attention than the bytes saved.

The documentation is done when a new owner can add a hook, run the build, and see the cost in the diff.

Curated: · Written: · Reviewed:

Difficulty: Medium