On this page

React Interview Questions

React interviews test three things: whether you understand the rendering model, whether you can build real features with hooks, and whether you know when React is the wrong tool for a problem. This page covers the questions that separate candidates who have used React from candidates who understand React.

How to use this page

The questions are grouped by level and then by topic:

LevelWhat the interviewer is checkingSections
JuniorYou can build components correctly and you know the rulesRendering basics, keys, core hooks, forms, conditional rendering
SeniorYou understand why the rules exist and can debug the hard casesFiber, batching, stale closures, effects, memoization, context, Suspense, concurrency, React 19, error boundaries, testing, build-it questions
StaffYou can make architecture decisions and defend themServer Components, streaming, hydration, the React Compiler, profiling methodology, state architecture, migrations

Every question follows the same shape: the answer, runnable code, the common wrong answer or trap, and the follow-up the interviewer is likely to ask next. If you can answer the follow-up without looking, you know the topic.

Versions referenced: React 19 (stable since December 2024), React 19.2 (October 2025, which added <Activity>, useEffectEvent and cacheSignal), and React Compiler 1.0 (stable since October 2025). Code examples assume a modern toolchain (Vite or Next.js) and React 19 unless they say otherwise.


Junior: Rendering and Reconciliation Basics

Q: What is the Virtual DOM and why does React use it?

The Virtual DOM is a lightweight JavaScript representation of the actual DOM. React maintains a virtual tree, and when state changes, it creates a new virtual tree, diffs it against the previous one, and applies only the minimal set of DOM mutations needed.

graph LR
    SC["State Change"] --> NV["New Virtual DOM"]
    OV["Previous Virtual DOM"] --> DIFF["Diffing Algorithm<br/>(Reconciliation)"]
    NV --> DIFF
    DIFF --> PATCH["Minimal DOM<br/>Mutations"]
    PATCH --> RD["Real DOM"]

    style SC fill:#dc2626,color:#fff
    style DIFF fill:#d97706,color:#fff
    style PATCH fill:#059669,color:#fff

Why not just update the real DOM directly?

  • DOM operations are expensive — they trigger layout recalculation, painting, and compositing.
  • Batching multiple updates into one DOM operation is far more efficient.
  • The diffing algorithm is O(n) — React compares nodes level by level, assuming:
    1. Elements of different types produce different trees.
    2. The key prop identifies which children remain stable across renders.

A "virtual DOM node" is just a plain object. JSX compiles to jsx() calls that return objects like { type: 'li', props: { children: 'Milk' }, key: null }. That is why rendering is cheap compared with touching the DOM: creating and comparing objects costs microseconds, while forcing layout can cost milliseconds.

The real reason React uses this model is not raw speed — hand-written DOM code can always be faster. It is the programming model: you describe what the UI should look like for a given state (UI = f(state)), and React works out how to get there. The diff is the price of that declarative model, and the heuristics keep it cheap.

Common wrong answer / trap: "The Virtual DOM makes React faster than the DOM." It does not; it adds work on top of the DOM. It makes declarative updates fast enough. Svelte and Solid skip the virtual DOM entirely and compile to direct DOM updates, which is a fair point to raise (see React vs Vue vs Svelte).

Follow-up: "Why is a generic tree diff O(n³) but React's is O(n)?" A minimal edit distance between two arbitrary trees needs about O(n³) work. React gives up optimality with two heuristics: it never matches nodes across levels, and it treats a change of element type as "throw the subtree away". Keys add identity within one list of siblings.

Q: Explain the reconciliation algorithm

React's reconciliation compares two virtual DOM trees. The key rules:

ScenarioReact's Behavior
Different element types (<div> → <span>)Destroy old tree, build new tree from scratch
Same element typeKeep the DOM node, update only changed attributes
Component type changesUnmount old component, mount new component
Lists without keysRe-render all items (worst case)
Lists with stable keysMatch items by key, minimize moves

Correction (2026-11-09): "Lists without keys: re-render all items" is imprecise. Without keys, React falls back to the array index as the key and logs a "each child in a list should have a unique key" warning. Every item re-renders anyway when the parent renders (keys do not prevent re-renders, only memo does). What goes wrong without keys is identity: an insert at the top makes React patch every existing DOM node and component with the next item's data. Component state and uncontrolled input values stay at their position and end up on the wrong item.

Keys Must Be Stable and Unique

Using array index as a key causes bugs when items are reordered, inserted, or deleted. The key must identify the data, not the position.

// BAD — index as key
{items.map((item, index) => <Item key={index} {...item} />)}

// GOOD — stable unique ID
{items.map(item => <Item key={item.id} {...item} />)}

The "component type changes" row catches people out when a component is defined inside another component:

function Parent() {
  // BUG: a new Input *type* is created on every render of Parent
  function Input() {
    const [text, setText] = useState('');
    return <input value={text} onChange={e => setText(e.target.value)} />;
  }
  const [, force] = useState(0);
  return (
    <>
      <Input />
      <button onClick={() => force(n => n + 1)}>Re-render parent</button>
    </>
  );
}
// Clicking the button resets the text: Input is a different function
// each render, so React unmounts the old one and mounts a new one.

Common wrong answer / trap: "React compares the old DOM with the new DOM." It compares the previous fiber tree (React elements plus state) with the new elements. It never reads the real DOM to diff.

Follow-up: "How do you deliberately reset a component's state?" Change its key: <Profile key={userId} userId={userId} />. A new key means a new identity, so React unmounts the old instance and mounts a fresh one. This is cleaner than an effect that resets state when a prop changes.

Q: Why is the array index a bad key, and when is it acceptable?

A key tells React which item a component instance belongs to. With index keys, identity is tied to position. Insert an item at the start and every position now holds different data, but React thinks positions 0..n-1 are the same components. State inside those components (an expanded flag, an uncontrolled input's text, focus, a running animation) stays with the position and ends up on the wrong item.

import { useState } from 'react';

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

export default function App() {
  const [items, setItems] = useState([{ id: 1, label: 'A' }, { id: 2, label: 'B' }]);
  const prepend = () => setItems([{ id: Date.now(), label: 'New' }, ...items]);
  return (
    <>
      <button onClick={prepend}>Prepend</button>
      {/* Type a note next to "A", then click Prepend. With key={i} the note */}
      {/* moves to "New". With key={item.id} it stays on "A".                  */}
      <ul>{items.map((item, i) => <Row key={i} label={item.label} />)}</ul>
    </>
  );
}

Index keys are acceptable when all three hold: the list is never reordered or filtered, items are never inserted or removed except at the end, and items have no state or uncontrolled inputs.

Common wrong answer / trap: "Use Math.random() or crypto.randomUUID() as the key in map." That produces a new key every render, so React unmounts and remounts every item each time. That is slower than index keys and it wipes all state. Generate the id once when the data is created, not during render.

Follow-up: "Do keys need to be globally unique?" No. They only need to be unique among siblings in the same array. Two different lists can both use key="1".

Q: What causes a component to re-render?

A component re-renders when:

  1. Its state changes: setState with a value that is not Object.is-equal to the current one.
  2. Its parent re-renders. By default, React re-renders all children of a component that rendered, whether or not their props changed.
  3. A context it reads changes: useContext(Ctx) or use(Ctx) subscribes the component.
  4. An external store it subscribes to changes (through useSyncExternalStore, which libraries like Zustand and Redux use).

Props changing is not a separate cause. Props only change because the parent re-rendered.

import { useState, memo } from 'react';

function Child() {
  console.log('Child rendered');
  return <p>I take no props</p>;
}
const MemoChild = memo(Child);

export default function Parent() {
  const [n, setN] = useState(0);
  return (
    <>
      <button onClick={() => setN(n + 1)}>{n}</button>
      <Child />      {/* logs on every click */}
      <MemoChild />  {/* logs once — props are shallow-equal */}
    </>
  );
}

Setting state to the same value usually bails out: setN(n) will not re-render the children. (React may still call the component function once before bailing, which is an implementation detail.)

Common wrong answer / trap: "A component re-renders when its props change." That is backwards. It re-renders when its parent renders, and the props may or may not have changed. This is why memo exists.

Follow-up: "How would you stop Child re-rendering without memo?" Move the state down into a smaller component, or lift the content up: pass <Child /> as children to the stateful component. An element that was created by the grandparent keeps the same reference when the stateful component re-renders, so React skips it.

Q: Controlled vs uncontrolled components — which should you use?

A controlled input gets its value from React state (value plus onChange). React is the source of truth, so every keystroke goes through a state update and a re-render. An uncontrolled input keeps its value in the DOM. You read it when you need it, through a ref or FormData on submit, and set the initial value with defaultValue.

import { useState, useRef } from 'react';

function Controlled() {
  const [email, setEmail] = useState('');
  const invalid = email !== '' && !email.includes('@'); // live validation is easy
  return (
    <>
      <input value={email} onChange={e => setEmail(e.target.value)} />
      {invalid && <span role="alert">Needs an @</span>}
    </>
  );
}

function Uncontrolled() {
  const ref = useRef(null);
  return (
    <form onSubmit={e => { e.preventDefault(); alert(ref.current.value); }}>
      <input ref={ref} defaultValue="hello" />
      <button>Submit</button>
    </form>
  );
}

Use controlled inputs when the UI depends on the value as you type (validation, formatting, conditional fields, a character counter). Use uncontrolled inputs for simple submit-and-forget forms, file inputs (always uncontrolled), and very large forms where re-rendering on every keystroke is costly. That is the whole idea behind React Hook Form. React 19's form Actions push the default towards uncontrolled: the action receives FormData.

Common wrong answer / trap: Writing <input value={name} /> with no onChange. React makes it read-only and warns. The other trap is switching between controlled and uncontrolled by starting with value={undefined} and later passing a string. Initialise with '', not undefined.

Follow-up: "Why can't a file input be controlled?" Its value can only be set by the user, for security reasons. Programmatically you can only clear it. You read input.files through a ref or from FormData.

Junior: Core Hooks

Q: Why are hooks called in a specific order?

React stores hooks for each component as a linked list. On each render, React walks the list in order. If a hook is called conditionally, the list length or order changes, and React maps the wrong state to the wrong hook.

graph LR
    subgraph "First Render"
        H1A["useState<br/>count: 0"] --> H2A["useEffect<br/>fetch data"] --> H3A["useMemo<br/>computed"]
    end

    subgraph "Second Render (correct)"
        H1B["useState<br/>count: 1"] --> H2B["useEffect<br/>fetch data"] --> H3B["useMemo<br/>computed"]
    end

    subgraph "Second Render (broken — conditional hook)"
        H1C["useState<br/>count: 1"] --> H2C["useMemo ???<br/>WRONG HOOK"] --> H3C["???"]
    end

    style H2C fill:#dc2626,color:#fff
    style H3C fill:#dc2626,color:#fff
// BAD — conditional hook
function Profile({ showAge }) {
  const [name, setName] = useState('');

  if (showAge) {
    const [age, setAge] = useState(0); // Breaks hook order
  }

  useEffect(() => { /* ... */ }); // Gets wrong position
}

// GOOD — hook always called, condition inside
function Profile({ showAge }) {
  const [name, setName] = useState('');
  const [age, setAge] = useState(0); // Always called

  useEffect(() => {
    if (showAge) {
      // Conditional logic inside the hook
    }
  }, [showAge]);
}

The two Rules of Hooks: only call hooks at the top level (not in loops, conditions, nested functions, or after an early return), and only call them from React function components or custom hooks. eslint-plugin-react-hooks enforces both and should always be on.

You can see why the ordering matters with a toy version of useState in plain JavaScript. It keeps state in an array indexed by call order, much as React's linked list does:

// Run with node: a toy model of how hooks are stored by call order.
let hooks = [], i = 0;
function useState(init) {
  const idx = i++;
  if (hooks[idx] === undefined) hooks[idx] = init;
  return [hooks[idx], v => { hooks[idx] = v; }];
}
function render(showAge) {
  i = 0;
  const [name] = useState('Ada');
  if (showAge) useState(36);      // conditional hook
  const [city] = useState('London');
  return { name, city };
}
console.log(render(true));   // { name: 'Ada', city: 'London' }
console.log(render(false));  // { name: 'Ada', city: 36 }  ← city reads age's slot

Common wrong answer / trap: "An early return before a hook is fine because the hook is still at the top level of the function." It is not. if (!user) return null; placed above a useEffect changes the number of hooks between renders, and React throws "Rendered fewer hooks than expected."

Follow-up: "The new use API can be called inside an if. Doesn't that break the rule?" use is not a hook in the storage sense. It does not keep a slot in the hook list; it reads a promise or context at that moment. That is why React documents it as the exception that may be called conditionally and in loops (though still not inside try/catch).

Q: useState — why does console.log(count) right after setCount show the old value?

State is a snapshot per render. setCount does not change the count variable. It queues an update and schedules a re-render, and in that next render the component function runs again and useState returns the new value. Inside the current event handler, count is a const captured from the render that created the handler.

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

  function handleClick() {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
    console.log(count); // 0 — still this render's snapshot
  }
  // After the click, count is 1, not 3: all three calls computed 0 + 1.

  function handleClickFixed() {
    setCount(c => c + 1);
    setCount(c => c + 1);
    setCount(c => c + 1); // updater functions chain: 0 → 1 → 2 → 3
  }

  return <button onClick={handleClickFixed}>{count}</button>;
}

Use the updater form (setX(prev => next)) whenever the next state depends on the previous state, especially from timers, effects, subscriptions and async callbacks, where the closure may be stale.

Common wrong answer / trap: "setState is async, so add an await." It does not return a promise, so awaiting it does nothing. It is not "async" in the promise sense. It is deferred to the next render. If you need the new value straight away, compute it into a local variable and use that.

Follow-up: "What about objects in state?" State must be replaced, not mutated: setUser({ ...user, name }). Mutating user.name = x; setUser(user) passes the same reference, Object.is says nothing changed, and React bails out of the render.

Q: useEffect cleanup and dependency array

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

  useEffect(() => {
    // Setup: subscribe to the room
    const connection = createConnection(roomId);
    connection.on('message', (msg) => {
      setMessages(prev => [...prev, msg]);
    });
    connection.connect();

    // Cleanup: runs before re-running effect or on unmount
    return () => {
      connection.disconnect();
    };
  }, [roomId]); // Only re-run when roomId changes

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

Dependency array rules:

Dependency ArrayEffect Runs
Not providedAfter every render
[]Once on mount, cleanup on unmount
[a, b]When a or b changes (Object.is comparison)

The useful mental model is synchronisation, not lifecycle. An effect keeps an external system (a socket, a subscription, a DOM API, a timer) in sync with the current props and state. When roomId changes from "general" to "music", React runs the cleanup from the "general" render (disconnect general) and then the setup with "music" (connect music). Every setup needs a matching cleanup.

Order on an update: render → commit DOM → old cleanup → new setup. On unmount, only the cleanup runs. In development under <StrictMode>, React runs setup → cleanup → setup once on mount, to prove that the cleanup really undoes the setup.

Common wrong answer / trap: "[] means 'run once', so I'll use it to fetch and leave out the props I use." Leaving out a dependency is lying to React. When the prop changes, the effect keeps using the old value. The linter flags it, so fix the code rather than silencing the rule.

Follow-up: "Why does my effect run twice in development?" StrictMode double-invokes mount effects to surface missing cleanups. It happens only in development. The fix is a correct cleanup (abort the fetch, unsubscribe), not a useRef guard that skips the second run.

Q: useRef vs useState — when do you use each?

Both persist a value across renders. The difference: changing state schedules a re-render, while changing ref.current does not. Use state for anything the UI displays. Use a ref for values that are needed by event handlers or effects but not by render: timer ids, the previous value, a DOM node, an AbortController, a "latest callback".

import { useRef, useState } from 'react';

function Stopwatch() {
  const [elapsed, setElapsed] = useState(0);   // displayed → state
  const intervalRef = useRef(null);            // not displayed → ref

  const start = () => {
    if (intervalRef.current) return;
    const t0 = Date.now() - elapsed;
    intervalRef.current = setInterval(() => setElapsed(Date.now() - t0), 50);
  };
  const stop = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  };

  return (
    <>
      <p>{(elapsed / 1000).toFixed(2)}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </>
  );
}

Common wrong answer / trap: Reading or writing ref.current during render to drive output, for example return <p>{renderCount.current++}</p>. That makes render impure. It double-counts under StrictMode and confuses the React Compiler. The rule is: refs are for event handlers and effects. (The one accepted pattern is lazy initialisation: if (ref.current === null) ref.current = new Thing().)

Follow-up: "How do you get a ref to a child component's DOM node?" In React 19, pass ref as a normal prop to a function component and put it on the DOM element. Before React 19 you needed forwardRef. To expose a custom API instead of the node, use useImperativeHandle.


Senior: Rendering Internals

Q: What is React Fiber?

Fiber is the reimplementation of React's core algorithm (introduced in React 16). The key insight: rendering work can be split into chunks and spread across multiple frames, allowing the browser to handle high-priority work (user input, animations) between chunks.

graph TD
    subgraph "Old Stack Reconciler"
        A1["Start Render"] --> A2["Process Entire Tree<br/>(synchronous, blocking)"] --> A3["Commit to DOM"]
    end

    subgraph "Fiber Reconciler"
        B1["Start Render"] --> B2["Process Unit of Work"]
        B2 --> B3{"More work?"}
        B3 -->|"Yes"| B4{"Higher priority<br/>work waiting?"}
        B4 -->|"No"| B2
        B4 -->|"Yes"| B5["Yield to Browser<br/>(user input, paint)"]
        B5 --> B2
        B3 -->|"No"| B6["Commit to DOM<br/>(synchronous, cannot interrupt)"]
    end

    style A2 fill:#dc2626,color:#fff
    style B5 fill:#059669,color:#fff

Each fiber node stores:

  • Type of component/element
  • Pending props and state
  • Pointer to parent, child, and sibling fiber nodes
  • Effect tags (placement, update, deletion)
  • Priority lane

Correction (2026-11-09): In current React source, "effect tags" are called flags (fiber.flags, with subtreeFlags so React can skip subtrees that have nothing to commit). The concept is the same, but the name has been out of date since React 17/18. A fiber also holds memoizedState (the head of the hook linked list), alternate (the matching fiber in the other tree), and lanes/childLanes.

Two-Phase Rendering

Fiber splits rendering into two phases:

  1. Render phase (interruptible) — determines what changes are needed
  2. Commit phase (synchronous) — applies changes to the DOM

Side effects (DOM mutations, refs, lifecycle methods) only happen in the commit phase.

React uses double buffering. The current tree is what is on screen. Work happens on a workInProgress tree, built from the alternate fibers. At commit, React swaps the pointer. Because the render phase can be paused, thrown away and restarted, render must be pure: React may call your component function several times for one commit.

Interruptibility only applies to concurrent renders: those started by startTransition, useDeferredValue or Suspense retries. A normal setState from a click is rendered synchronously at the highest-priority lane.

Common wrong answer / trap: "Fiber makes React multi-threaded." It does not. All of it runs on the main thread. Fiber turns rendering into units of work that can be paused and resumed. In concurrent renders the scheduler yields roughly every 5 ms so the browser can handle input.

Follow-up: "What are lanes?" Lanes are a 31-bit bitmask of priorities (SyncLane, InputContinuousLane, DefaultLane, TransitionLanes, IdleLane and others). Bitmasks let React batch updates of the same priority together, and let it pick the highest-priority pending work cheaply.

Q: Explain React's batching behavior

React 18 introduced automatic batching for all updates, not just event handlers.

// React 17 — only batched inside event handlers
function handleClick() {
  setCount(c => c + 1);
  setFlag(f => !f);
  // One re-render (batched)
}

setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // TWO re-renders in React 17 (not batched)
  // ONE re-render in React 18 (automatic batching)
}, 1000);

// To opt out of batching (rare):
import { flushSync } from 'react-dom';

flushSync(() => { setCount(c => c + 1); });
// DOM updated here
flushSync(() => { setFlag(f => !f); });
// DOM updated here

Automatic batching needs the createRoot API. A legacy ReactDOM.render root in React 18 kept the old behaviour, and React 19 removed ReactDOM.render altogether. Updates are batched per task: everything queued in the same synchronous run of code (or the same microtask) is flushed together. Updates on either side of an await belong to different tasks, so they render separately.

async function handleSave() {
  setSaving(true);          // render #1 (flushed before the await resumes)
  await api.save(form);
  setSaving(false);         // ┐ batched together
  setSavedAt(Date.now());   // ┘ render #2
}

Common wrong answer / trap: "Batching means setState is asynchronous, so I can't read the DOM after it." That is true, and the fix is flushSync when you must measure or scroll straight after an update, for example scrolling to a newly added list item. Use it rarely, because it forces a synchronous render.

Follow-up: "When would you use flushSync?" Scroll-to-new-item, focus management after a state change that renders the target, and window.print() after updating print-only state.

Senior: Hooks Pitfalls

Q: What is a stale closure, and how do you fix one?

Each render creates new functions that close over that render's props and state. If a function is created once and kept, by an effect with [], a setInterval, a subscription or a memoised callback, it keeps reading the values from the render that created it.

Common Pitfall: Stale Closures

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

  useEffect(() => {
    const id = setInterval(() => {
      // BUG: `count` is captured as 0, never updates
      setCount(count + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []); // Empty deps — closure captures initial count

  // FIX: use functional updater
  useEffect(() => {
    const id = setInterval(() => {
      setCount(prev => prev + 1); // Always uses latest state
    }, 1000);
    return () => clearInterval(id);
  }, []);
}

The fixes, in order of preference:

  1. Updater function when the stale value is state you are updating: setCount(c => c + 1).
  2. Declare the dependency honestly ([count]) and let the effect re-subscribe. This is often fine.
  3. useEffectEvent (stable in React 19.2) for logic inside an effect that must read the latest props without re-running the effect:
import { useEffect, useEffectEvent } from 'react';

function ChatRoom({ roomId, theme }) {
  const onConnected = useEffectEvent(() => {
    showNotification('Connected!', theme); // always the latest theme
  });

  useEffect(() => {
    const conn = createConnection(roomId);
    conn.on('connected', () => onConnected());
    conn.connect();
    return () => conn.disconnect();
  }, [roomId]); // theme changes do NOT reconnect; onConnected is not a dependency
}
  1. The "latest ref" pattern (before 19.2): store the callback in a ref, update it in an effect, and read ref.current inside the long-lived closure.

Common wrong answer / trap: Disabling react-hooks/exhaustive-deps to "stop the effect re-running". The closure is still stale; you have just hidden the warning. Another trap is calling an Effect Event from an event handler or passing it to children. It is meant to be called only from inside effects.

Follow-up: "Why can't the updater form fix a stale prop?" Updaters only receive the previous state. For a stale prop you need the dependency, an Effect Event, or a ref.

Q: My effect runs in an infinite loop. Why?

Dependencies are compared with Object.is. An object, array or function created during render is a new reference on every render, so an effect that depends on it runs after every render. If that effect also sets state, the state update causes a render, which creates a new object, which runs the effect again, and so on forever.

// Run with node — why fresh objects always look "changed":
console.log(Object.is([], []), Object.is(NaN, NaN), Object.is(0, -0));
// false true false
// BAD — options is a new object every render → effect every render → setState → loop
function Results({ query }) {
  const [data, setData] = useState(null);
  const options = { query, limit: 20 };
  useEffect(() => {
    search(options).then(setData);
  }, [options]);
}

// GOOD — depend on primitives, build the object inside the effect
function Results({ query }) {
  const [data, setData] = useState(null);
  useEffect(() => {
    let ignore = false;
    search({ query, limit: 20 }).then(d => { if (!ignore) setData(d); });
    return () => { ignore = true; }; // also fixes the out-of-order response race
  }, [query]);
}

Fixes: move the object or function inside the effect; hoist constants outside the component; depend on primitive fields (user.id, not user); or, as a last resort, memoise with useMemo or useCallback.

Common wrong answer / trap: Wrapping everything in useCallback to make the loop stop. It works, but it treats the symptom. Usually the effect should not exist at all (see the next question), or the object should be built inside it.

Follow-up: "What's the ignore flag for?" Race conditions. If query changes from "a" to "ab" and the response for "a" arrives last, it would overwrite the newer results. The cleanup marks the old request as ignored. With fetch, use AbortController instead and the old request is cancelled.

Q: "You might not need an effect" — what should not be an effect?

Effects are for synchronising with external systems. Many effects in real codebases are just roundabout ways of computing values or handling events. They cost an extra render and introduce bugs.

Instead of an effect that...Do this
Sets state derived from props/state (setFullName(first + ' ' + last))Compute during render: const fullName = first + ' ' + last
Caches an expensive derivationuseMemo (or let the Compiler do it)
Resets all state when a prop changeskey={id} on the component
Adjusts some state when a prop changesStore the previous prop and update during render, or restructure
Reacts to a user action (POST on submit, toast on click)Do it in the event handler
Notifies the parent of a state change (onChange(value) in an effect)Call onChange in the same handler that sets state
Fetches dataA framework loader, TanStack Query, or use() with a cached promise
// BAD — extra render plus a one-frame flash of stale filteredTodos
const [filtered, setFiltered] = useState([]);
useEffect(() => { setFiltered(todos.filter(t => t.done === showDone)); }, [todos, showDone]);

// GOOD
const filtered = todos.filter(t => t.done === showDone);

Common wrong answer / trap: "Effects are where side effects go, and a POST is a side effect." An effect runs because the component rendered, not because the user did something. A POST in an effect fires again on remount, under StrictMode, and after Fast Refresh. User-caused side effects belong in event handlers or Actions.

Follow-up: "Then what legitimately needs an effect?" Subscribing to a browser API or WebSocket, integrating a non-React widget (a map or chart library), focus management, analytics page views, and synchronising with document.title (though React 19 can render <title> directly).

Q: useLayoutEffect vs useEffect — and when does useEffect run before paint?

useLayoutEffect runs synchronously after the DOM is mutated and before the browser paints. Use it to measure layout and apply a correction (tooltip positioning, scroll restoration, avoiding a flicker). useEffect normally runs after paint, so it does not block the frame.

import { useLayoutEffect, useRef, useState } from 'react';

function Tooltip({ anchorRect, children }) {
  const ref = useRef(null);
  const [top, setTop] = useState(0);

  useLayoutEffect(() => {
    const { height } = ref.current.getBoundingClientRect();
    // Flip above the anchor if there's no room below — before the user sees anything.
    const below = anchorRect.bottom + height < window.innerHeight;
    setTop(below ? anchorRect.bottom : anchorRect.top - height);
  }, [anchorRect]);

  return <div ref={ref} style={{ position: 'fixed', top }}>{children}</div>;
}

Correction (2026-11-09): The quick-fire answer below says useEffect "fires asynchronously after paint". That is the usual case, but not guaranteed. Since React 18, when an update comes from a discrete user input (click, keydown), React flushes the resulting passive effects synchronously before the browser paints. Effects also flush early whenever another update needs to render first. Only useLayoutEffect guarantees running before paint; do not rely on useEffect being either before or after.

Common wrong answer / trap: Using useLayoutEffect "to be safe". It blocks paint, and on the server it does nothing (React 18 printed a warning about this, React 19 does not). Code that needs layout should be client-only anyway.

Follow-up: "What's useInsertionEffect?" It runs before layout effects, and it is for CSS-in-JS libraries to inject <style> tags before anything reads layout. Application code almost never needs it.

Senior: Memoization

Q: useMemo vs useCallback — when do they actually help?

Both are optimization hooks. useMemo caches a computed value. useCallback caches a function reference.

// useMemo — expensive computation
function Dashboard({ transactions }) {
  // Without useMemo: recalculates on every render
  const stats = useMemo(() => {
    return {
      total: transactions.reduce((sum, t) => sum + t.amount, 0),
      average: transactions.reduce((sum, t) => sum + t.amount, 0) / transactions.length,
      max: Math.max(...transactions.map(t => t.amount)),
    };
  }, [transactions]);

  return <StatsPanel stats={stats} />;
}

// useCallback — stable function reference for memoized children
function Parent() {
  const [count, setCount] = useState(0);

  // Without useCallback: new function reference every render,
  // causing ExpensiveChild to re-render
  const handleClick = useCallback((id) => {
    console.log('Clicked:', id);
  }, []); // No dependencies — function never changes

  return (
    <>
      <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>
      <ExpensiveChild onClick={handleClick} />
    </>
  );
}

const ExpensiveChild = React.memo(({ onClick }) => {
  // Expensive render...
  return <div onClick={() => onClick(42)}>Click me</div>;
});

When Memoization Hurts

useMemo and useCallback have overhead — they store previous values and compare dependencies. Do not memoize everything. Memoize when:

  • The computation is genuinely expensive (>1ms)
  • The value is passed to a React.memo wrapped child
  • The value is a dependency of another hook

Do not memoize primitive values, simple object literals used in the same component, or cheap computations.

useCallback(fn, deps) is exactly useMemo(() => fn, deps). To measure "expensive", wrap the computation in console.time and use a 4x–6x CPU slowdown in DevTools. Your laptop is not your users' phone.

Common wrong answer / trap: "useMemo guarantees the value is only computed once." React documents it as a performance hint. It may throw the cache away (for example for offscreen content, or during development edits). Never rely on it for correctness, such as keeping a single instance of a connection. Use a ref or module state for that.

Follow-up: "With the React Compiler, do you still write these?" Mostly not in new code. The compiler memoises automatically, and at a finer grain, including after early returns, which hooks cannot do. The React team still recommends useMemo and useCallback as escape hatches, for example to keep an effect dependency stable. See the React Compiler question.

Q: React.memo — when and how

React.memo is a higher-order component that skips re-rendering when props have not changed (shallow comparison).

// Only re-renders when `items` or `onSelect` references change
const ItemList = React.memo(function ItemList({ items, onSelect }) {
  console.log('ItemList rendered');
  return (
    <ul>
      {items.map(item => (
        <li key={item.id} onClick={() => onSelect(item.id)}>
          {item.name}
        </li>
      ))}
    </ul>
  );
});

// Custom comparison function
const ChartWidget = React.memo(
  function ChartWidget({ data, config }) {
    return <canvas ref={drawChart(data, config)} />;
  },
  (prevProps, nextProps) => {
    // Return true to SKIP re-render
    return (
      prevProps.data.length === nextProps.data.length &&
      prevProps.config.type === nextProps.config.type
    );
  }
);

memo only skips re-renders caused by the parent. A memoised component still re-renders when its own state changes or a context it reads changes. The custom comparator above is risky: if data changes content but keeps its length, the chart goes stale. A custom comparator must compare every prop that affects output, including functions.

Common wrong answer / trap: Wrapping a component in memo and then passing it an inline style object literal, onClick={() => ...} or children. Each of those is a new reference every render, so the shallow comparison always fails and memo only adds the cost of comparing. children is the subtle one: <Memo><span /></Memo> creates a new element object on every render.

Follow-up: "How do you confirm memo is working?" Use the React DevTools Profiler with "Record why each component rendered" turned on. Memoised components that skipped appear greyed out, and the panel names the prop that changed.

Q: When are useMemo, useCallback and memo pointless?

They are pointless, or harmful, when:

  1. The child isn't memoised. useCallback on a handler passed to a plain <button> or to a non-memo component saves nothing. The child re-renders anyway.
  2. Another prop breaks memoisation. One inline object or children prop makes all the other careful memoisation useless.
  3. The computation is cheap. Filtering 50 items costs microseconds. The dependency array comparison plus the closure allocation cost about as much.
  4. The dependencies change on every render anyway. useMemo(() => f(obj), [obj]), where obj is created inline, recomputes every time.
  5. The real problem is the component structure. Moving state down, or passing content in as children, removes the re-render completely, with no memoisation at all.
  6. The React Compiler is on. It already memoises, so hand-written hooks are redundant (though harmless).
// Pointless: Button isn't memoised, so it re-renders anyway
const onClick = useCallback(() => setOpen(true), []);
return <Button onClick={onClick} />;

// Better than any memo: isolate the fast-changing state
function SearchPage() {
  return (
    <>
      <SearchBox />        {/* owns its own query state */}
      <ExpensiveSidebar /> {/* no longer re-renders on keystrokes */}
    </>
  );
}

Common wrong answer / trap: "Memoise everything; it can't hurt." It costs memory, makes the code harder to read, and creates a false sense of stability. A later edit that adds an inline prop silently undoes it.

Follow-up: "Name a case where useCallback is required for correctness, not speed." When the function is an effect dependency. Without it, the effect re-subscribes every render. In React 19.2 or later, useEffectEvent is usually the better fix.

Senior: State Management and Context

Q: When to lift state, when to use context, when to use a library?

graph TD
    A["Where does the state belong?"]
    B["Used by one component?<br/>→ Local useState"]
    C["Shared by parent-child?<br/>→ Lift to closest common parent"]
    D["Shared by distant siblings?<br/>→ Context or state library"]
    E["Updated frequently?<br/>(every keystroke, animation)<br/>→ State library or useRef"]
    F["Server state?<br/>(API data, cache)<br/>→ TanStack Query / SWR"]

    A --> B
    A --> C
    A --> D
    D --> E
    A --> F

    style B fill:#059669,color:#fff
    style F fill:#0891b2,color:#fff
ScenarioSolutionWhy
Form input stateuseState in the form componentLocal, no sharing needed
Theme/localeReact ContextChanges rarely, many consumers
Shopping cartZustand or JotaiUpdated from many components, needs persistence
API dataTanStack QueryHandles caching, revalidation, loading states
Complex formsReact Hook FormPerformance — avoids re-rendering on every keystroke
High-frequency updatesuseRef + external storeContext re-renders all consumers on every change

Two more categories are often missed. URL state (filters, tabs, pagination) belongs in the query string, so it survives a refresh and can be shared. Server state is not really your state; it is a cache of somebody else's. Most "we need Redux" problems turn out to be server-state caching problems that TanStack Query or a framework's loader solves better. Stores such as Zustand let a component subscribe to a slice (useCart(s => s.items.length)), so it re-renders only when that slice changes.

Common wrong answer / trap: "Redux for everything" or "Context for everything". Both are signs that the candidate has not classified the state first. Ask: who owns it (server, URL, or client), how often does it change, and how many components read it?

Follow-up: "How do you keep server data and client edits in sync?" Use the server cache as the source of truth, keep local edits as drafts, then invalidate or refetch after a mutation, with an optimistic update if needed (React 19's useOptimistic, or TanStack Query's onMutate).

Q: Why does Context cause performance issues?

When a Context value changes, every component consuming that context re-renders — even if it only uses a part of the value that did not change.

// BAD — one big context, everything re-renders
const AppContext = React.createContext();

function AppProvider({ children }) {
  const [user, setUser] = useState(null);
  const [theme, setTheme] = useState('light');
  const [notifications, setNotifications] = useState([]);

  return (
    <AppContext.Provider value={{
      user, setUser, theme, setTheme,
      notifications, setNotifications
    }}>
      {children}
    </AppContext.Provider>
  );
}
// Changing `theme` re-renders components that only use `user`

// GOOD — split into separate contexts
const UserContext = React.createContext();
const ThemeContext = React.createContext();
const NotificationContext = React.createContext();

There is a second, sneakier problem in the BAD example. The value object literal is new on every render of AppProvider, so all consumers re-render whenever the provider's parent renders, even when nothing in the value changed. Memoise the value. Splitting state from dispatch also helps, because components that only call setX then never re-render:

import { createContext, useContext, useMemo, useState } from 'react';

const ThemeValue = createContext('light');
const ThemeSetter = createContext(() => {});

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  // React 19: render <Context> directly instead of <Context.Provider>
  return (
    <ThemeSetter value={setTheme}>      {/* setState is stable, never changes */}
      <ThemeValue value={theme}>{children}</ThemeValue>
    </ThemeSetter>
  );
}

export const useTheme = () => useContext(ThemeValue);
export const useSetTheme = () => useContext(ThemeSetter); // toggles never re-render on theme change

// When a provider has to expose an object, memoise it:
// const value = useMemo(() => ({ user, login, logout }), [user]);

Note that children passed into the provider does not re-render when the provider's state changes, because those elements were created by the provider's parent. Only consumers re-render.

Common wrong answer / trap: "Wrap consumers in React.memo to stop context re-renders." memo does not block context updates. A component that reads the context re-renders regardless. The fixes are splitting the context, putting a memoised child underneath the consumer, or a store with selectors.

Follow-up: "Is there a context selector?" Not in React core (there was an RFC). Libraries such as use-context-selector emulate one, and external stores (Zustand, Redux, Jotai) expose selectors through useSyncExternalStore.

Senior: Suspense and Concurrency

Q: Code splitting with lazy and Suspense

import { lazy, Suspense } from 'react';

// Lazy-load heavy components
const AdminDashboard = lazy(() => import('./AdminDashboard'));
const AnalyticsChart = lazy(() => import('./AnalyticsChart'));

function App() {
  return (
    <Suspense fallback={<Spinner />}>
      <Routes>
        <Route path="/admin" element={<AdminDashboard />} />
        <Route path="/analytics" element={<AnalyticsChart />} />
      </Routes>
    </Suspense>
  );
}

When a component inside the boundary suspends, because a lazy module or a promise read with use is not ready yet, React shows the nearest <Suspense> fallback. When the data is ready, it retries the render. Boundaries can be nested, so a slow widget does not blank the whole page. lazy must be called at module level, and the module needs a default export.

Common wrong answer / trap: Calling lazy() inside a component. That creates a new component type on every render, so it remounts and refetches forever. A second trap: a navigation that suspends an already-visible boundary swaps the content for a spinner. Wrap the navigation in startTransition and React keeps the old UI on screen instead.

Follow-up: "How do you avoid a waterfall of lazy chunks?" Start loading early: call the import() on hover or intent, or let the router preload route chunks. Start data fetching in parallel with the chunk, not inside the component after it loads.

Q: useTransition — what does it solve?

startTransition marks a state update as non-urgent. React renders it at a lower priority, interruptibly, in the background, while urgent updates like typing stay responsive. isPending tells you that the transition is in progress. If an urgent update arrives, React abandons the half-finished transition render and starts again with the latest state.

import { useState, useTransition } from 'react';

function TabContainer() {
  const [tab, setTab] = useState('about');
  const [isPending, startTransition] = useTransition();

  function select(next) {
    startTransition(() => setTab(next)); // slow tab render won't freeze the buttons
  }

  return (
    <>
      <nav style={{ opacity: isPending ? 0.6 : 1 }}>
        {['about', 'posts', 'contact'].map(t => (
          <button key={t} onClick={() => select(t)}>{t}</button>
        ))}
      </nav>
      {tab === 'posts' ? <SlowPosts /> : <p>{tab}</p>}
    </>
  );
}

In React 19 the function passed to startTransition can be async. That is what an "Action" is (next section).

Common wrong answer / trap: Wrapping a controlled input's setValue in a transition. Input updates must be urgent, or the field lags behind the keyboard. Keep the input state urgent and either transition the expensive derived state or use useDeferredValue. Another trap: transitions do not debounce and do not make the slow render itself faster. They only make it interruptible.

Follow-up: "useTransition vs the standalone startTransition import?" Same behaviour, but the standalone function gives you no isPending. It is meant for code outside components, such as routers and stores.

Q: useDeferredValue vs useTransition vs debounce

useDeferredValue(value) returns a copy of the value that "lags behind". On an urgent update, React first re-renders with the old deferred value, then starts a background render with the new one, which can be interrupted. Use it when you do not own the state update (it arrives as a prop), or when you want to keep the input urgent and the results deferred.

import { useState, useDeferredValue, memo } from 'react';

export default function Search() {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);
  const stale = query !== deferredQuery;

  return (
    <>
      <input value={query} onChange={e => setQuery(e.target.value)} />
      <div style={{ opacity: stale ? 0.5 : 1 }}>
        <SlowList query={deferredQuery} />
      </div>
    </>
  );
}

// MUST be memoised — otherwise it re-renders with the urgent update anyway.
const SlowList = memo(function SlowList({ query }) {
  const items = [];
  for (let i = 0; i < 250; i++) items.push(<SlowItem key={i} text={query} />);
  return <ul>{items}</ul>;
});
ToolDelaysGood for
DebounceThe update by a fixed timeNetwork requests (fewer calls)
useTransitionNothing; render is interruptibleYou own the setter; navigation; Actions
useDeferredValueThe value; adapts to device speedValue comes from props; slow render below a fast input

Common wrong answer / trap: Forgetting memo on the slow child, which removes the whole benefit. Another trap is thinking useDeferredValue reduces network requests. It does not: every keystroke still produces a render. Debounce the fetch.

Follow-up: "What's the second argument?" useDeferredValue(value, initialValue) (React 19). On the first render it returns initialValue, for example '', then renders the real value in the background. This is useful for showing a cheap placeholder quickly.

Senior: React 19

Q: What are Actions in React 19?

An Action is a function passed to a transition, and it can be async. React tracks the pending state, errors and optimistic updates for you. Any function you pass to startTransition, <form action={fn}>, <button formAction={fn}> or useActionState is treated as an Action. Before React 19, you managed isPending, error state and race conditions by hand in every handler.

import { useState, useTransition } from 'react';

function UpdateName() {
  const [name, setName] = useState('');
  const [error, setError] = useState(null);
  const [isPending, startTransition] = useTransition();

  const handleSubmit = () => {
    startTransition(async () => {                // async transition = Action
      const err = await updateName(name);
      if (err) { setError(err); return; }
      startTransition(() => redirect('/profile')); // state set after await needs its own transition (current limitation)
    });
  };

  return (
    <>
      <input value={name} onChange={e => setName(e.target.value)} />
      <button onClick={handleSubmit} disabled={isPending}>Update</button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}

With a <form action={fn}>, React calls fn(formData) inside a transition, and resets uncontrolled fields once the action succeeds. Child components can read the parent form's pending state with useFormStatus() from react-dom.

import { useFormStatus } from 'react-dom';

function SubmitButton() {
  const { pending } = useFormStatus(); // must be rendered INSIDE the <form>
  return <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>;
}

Common wrong answer / trap: Calling useFormStatus in the same component that renders the <form>. It reads the status of a parent form, so it returns pending: false there. A second trap is not knowing that state updates after an await inside a transition are not yet automatically part of it. The React docs say to wrap them in another startTransition.

Follow-up: "What happens if two submissions overlap?" Updates from Actions are batched, and with useActionState they are queued and run one after another, each receiving the previous result. For parallel, independent work, use useState with useTransition instead.

Q: How does useActionState work?

const [state, dispatchAction, isPending] = useActionState(reducerAction, initialState, permalink?);

The action receives (previousState, payload). When the action is used as a form action, the payload is FormData, so the form data is the second argument. Whatever the action returns becomes the new state. It can be async and may have side effects (unlike a useReducer reducer). Dispatches are queued and run one after another. If the action throws, the queue is cancelled and the error goes to the nearest error boundary, so return expected errors as state instead of throwing. The optional permalink lets a Server Function form work before JavaScript has loaded (progressive enhancement).

import { useActionState } from 'react';

async function subscribe(prevState, formData) {
  const email = formData.get('email');
  if (!String(email).includes('@')) return { ok: false, message: 'Invalid email' };
  const res = await fetch('/api/subscribe', { method: 'POST', body: formData });
  return res.ok ? { ok: true, message: 'Subscribed!' } : { ok: false, message: 'Try again' };
}

export default function Newsletter() {
  const [state, formAction, isPending] = useActionState(subscribe, { ok: null, message: '' });
  return (
    <form action={formAction}>
      <input name="email" type="email" required />
      <button disabled={isPending}>{isPending ? 'Subscribing…' : 'Subscribe'}</button>
      {state.message && <p role={state.ok ? 'status' : 'alert'}>{state.message}</p>}
    </form>
  );
}

Common wrong answer / trap: Writing the action as async (formData) => .... The first argument is the previous state, so formData.get throws. Another trap is calling dispatchAction() from a plain onClick without startTransition. Then isPending does not update, and React warns. (Older Canary builds called this hook useFormState in react-dom; it was renamed.)

Follow-up: "How do you reset it?" There is no built-in reset. Dispatch a reset payload that your action handles, or change the component's key.

Q: How does useOptimistic work?

const [optimisticState, setOptimistic] = useOptimistic(value, reducer?);

While an Action is pending, optimisticState shows what you set. When the Action finishes, it goes back to value, which is by then the real updated value. On failure it rolls back to the old value without any extra code. The setter must be called inside an Action (a transition or a form action). Outside one, React warns and the optimistic value only flashes briefly.

import { useOptimistic, useState, startTransition } from 'react';

function Thread({ initial, sendMessage }) {
  const [messages, setMessages] = useState(initial);
  const [optimistic, addOptimistic] = useOptimistic(
    messages,
    (current, text) => [...current, { id: 'temp-' + text, text, sending: true }]
  );

  async function formAction(formData) {
    const text = formData.get('text');
    addOptimistic(text);                         // appears instantly
    const saved = await sendMessage(text);       // may throw → automatic rollback
    startTransition(() => setMessages(m => [...m, saved]));
  }

  return (
    <>
      {optimistic.map(m => <p key={m.id} style={{ opacity: m.sending ? 0.5 : 1 }}>{m.text}</p>)}
      <form action={formAction}><input name="text" /><button>Send</button></form>
    </>
  );
}

Prefer the reducer form for relative updates. React re-runs the reducer if value changes while the action is pending, so the result never goes stale. Absolute values and updater functions only see the state from when the action started.

Common wrong answer / trap: "Optimistic state must be cleared manually when the request finishes." It does not need to be. It is derived from value and converges in the same commit. A second trap: if you never update the real state (setMessages), the message disappears once the action finishes.

Follow-up: "How do you show an error after rollback?" Catch the error in the action and set error state, or return it through useActionState. The rollback itself is automatic.

Q: What is the use API?

use(resource) reads a promise or a context during render. For a promise, the component suspends until it resolves (showing the nearest <Suspense> fallback), and if it rejects the error goes to the nearest error boundary. Unlike hooks, use may be called inside if blocks and loops, but not inside try/catch.

// app/page.jsx — Server Component creates the promise (no await) and streams it to the client.
import { Suspense } from 'react';
import Comments from './Comments';

export default function Page() {
  const commentsPromise = fetchComments(); // start early
  return (
    <Suspense fallback={<p>Loading comments…</p>}>
      <Comments commentsPromise={commentsPromise} />
    </Suspense>
  );
}
// app/Comments.jsx — Client Component
'use client';
import { use } from 'react';

export default function Comments({ commentsPromise }) {
  const comments = use(commentsPromise);
  return comments.map(c => <p key={c.id}>{c.text}</p>);
}

export function Heading({ show }) {
  if (show) {
    const theme = use(ThemeContext); // conditional context read — allowed for use()
    return <h1 className={theme}>Hi</h1>;
  }
  return null;
}

Common wrong answer / trap: Creating the promise inside the client component that calls use, as in use(fetch(url)). Every render then creates a new promise, which suspends again, and the result is an infinite loop. The promise must be cached or created outside: in a Server Component, a loader, a cache, or a framework. React warns about "uncached promises" for this reason.

Follow-up: "Can use replace useEffect for fetching?" Only together with a cache (a framework, cache() in RSC, or a library). In that case yes, and it avoids the fetch-on-render effect waterfall. Without a cache, no.

Q: What changed with refs in React 19?

  1. ref is a normal prop for function components, so forwardRef is no longer needed. React plans to deprecate it.
  2. Ref callbacks can return a cleanup function. React calls it on detach instead of calling the callback with null.
  3. <Context> can be rendered directly as a provider, replacing <Context.Provider> (also new in 19, often asked in the same breath).
// React 19 — no forwardRef
function TextInput({ ref, label, ...rest }) {
  return <label>{label} <input ref={ref} {...rest} /></label>;
}

function Form() {
  const inputRef = useRef(null);
  return (
    <>
      <TextInput ref={inputRef} label="Name" />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  );
}

// Ref callback with cleanup — great for observers
function Observed() {
  return (
    <div ref={node => {
      const ro = new ResizeObserver(([e]) => console.log(e.contentRect.width));
      ro.observe(node);
      return () => ro.disconnect();   // runs when the node detaches
    }} />
  );
}

Common wrong answer / trap: An implicit return in a ref callback: ref={n => (instance = n)}. In React 19 the return value is treated as a cleanup function. TypeScript now rejects returning anything that is not a function, and the no-implicit-ref-callback-return codemod rewrites these.

Follow-up: "Does ref as a prop work for class components?" No. On a class component, ref still refers to the instance and is not passed as a prop.

Senior: Forms and Error Handling

Q: How do you build and validate forms in React 19?

Use three layers. Native HTML validation (required, type="email", pattern) costs nothing and helps accessibility. A form Action with useActionState handles submission and server-side errors. Client validation on blur gives quick feedback. Server validation is still mandatory, because the client cannot be trusted. React Hook Form with a Zod schema is the common choice for large forms (uncontrolled inputs, so few re-renders).

import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';

async function signup(prev, formData) {
  const fields = Object.fromEntries(formData);
  const errors = {};
  if (fields.password.length < 12) errors.password = 'At least 12 characters';
  if (fields.password !== fields.confirm) errors.confirm = 'Passwords differ';
  if (Object.keys(errors).length) return { errors, fields }; // keep values on error
  await api.signup(fields);
  return { errors: {}, fields: {}, done: true };
}

function Submit() {
  const { pending } = useFormStatus();
  return <button disabled={pending}>Create account</button>;
}

export function Signup() {
  const [state, action] = useActionState(signup, { errors: {}, fields: {} });
  return (
    <form action={action} noValidate={false}>
      <input name="email" type="email" required defaultValue={state.fields.email} />
      <input name="password" type="password" aria-invalid={!!state.errors.password}
             aria-describedby="pw-err" required />
      <span id="pw-err">{state.errors.password}</span>
      <input name="confirm" type="password" required />
      <span>{state.errors.confirm}</span>
      <Submit />
    </form>
  );
}

Common wrong answer / trap: Forgetting that form Actions reset uncontrolled fields after a successful submission. If validation fails you need to send the values back (as above), or the user's input disappears. Validating only on the client is the other classic trap.

Follow-up: "How do you make errors accessible?" Use aria-invalid, link the message with aria-describedby, move focus to the first invalid field, and announce a summary with role="alert".

Q: What are error boundaries and what do they not catch?

An error boundary is a component that catches errors thrown while rendering, in lifecycle methods and in constructors of its descendants, and shows a fallback instead of unmounting the whole app. Since React 16, an uncaught render error unmounts the entire root, so boundaries are how you contain failures. They are still written as class components (getDerivedStateFromError plus componentDidCatch); there is no hook equivalent. Most teams use the react-error-boundary package.

import { Component } from 'react';

class ErrorBoundary extends Component {
  state = { error: null };
  static getDerivedStateFromError(error) { return { error }; }        // render fallback
  componentDidCatch(error, info) { report(error, info.componentStack); } // log
  render() {
    if (this.state.error) {
      return (
        <div role="alert">
          <p>Something went wrong.</p>
          <button onClick={() => this.setState({ error: null })}>Retry</button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage: granular boundaries, reset when the route changes
<ErrorBoundary key={location.pathname}><Dashboard /></ErrorBoundary>

They do not catch: errors in event handlers (use try/catch), async code outside render (setTimeout, un-awaited promises), errors during SSR, or errors thrown in the boundary itself. A rejected promise read with use(), or an Action that throws, does reach the boundary, because React rethrows it during render. React 19 also added onCaughtError, onUncaughtError and onRecoverableError options to createRoot for central reporting.

Common wrong answer / trap: "Wrap the whole app in one boundary." Then one broken widget blanks the page. Put boundaries around independent regions (route, sidebar, each dashboard card), next to the Suspense boundaries.

Follow-up: "How do you surface an event-handler error to a boundary?" Store it in state and throw it during render (if (error) throw error). react-error-boundary's showBoundary does exactly this.

Senior: Testing

Q: How do you test React components?

Use React Testing Library with Vitest or Jest (see Jest vs Vitest). Test behaviour through the user's eyes: query by role, label and text, interact with user-event, assert on what the user would see. Mock at the network boundary (MSW), not inside your own modules. Keep end-to-end tests (Playwright) for full flows.

// Newsletter.test.jsx — Vitest + @testing-library/react + @testing-library/user-event
// (toHaveTextContent comes from @testing-library/jest-dom, loaded in the test setup file)
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { test, expect } from 'vitest';
import Newsletter from './Newsletter';

test('shows a validation error for a bad email', async () => {
  const user = userEvent.setup();
  render(<Newsletter />);

  await user.type(screen.getByRole('textbox', { name: /email/i }), 'nope');
  await user.click(screen.getByRole('button', { name: /subscribe/i }));

  expect(await screen.findByRole('alert')).toHaveTextContent('Invalid email');
});

Use the find* queries (which await) for anything asynchronous. Use queryBy* only to assert that something is absent. Test custom hooks through a small component, or with renderHook.

Common wrong answer / trap: Testing implementation details: component state, the number of times a hook ran, CSS class names, or snapshot tests of large trees. Those tests break on refactors and miss real bugs. The other classic is the "not wrapped in act(...)" warning. It means an update happened after the test stopped waiting. Await a findBy*, rather than wrapping things in act by hand.

Follow-up: "How do you test Server Components?" Async Server Components are not well supported by RTL yet. Test the data layer and the client components in isolation, and cover the composition with Playwright end-to-end tests.

Senior: Build-It Questions

Q: Write a custom hook for API data fetching (useFetch with abort)

function useApi(url, options = {}) {
  const [state, setState] = useState({
    data: null,
    error: null,
    loading: true,
  });

  const optionsRef = useRef(options);
  optionsRef.current = options;

  useEffect(() => {
    const abortController = new AbortController();

    async function fetchData() {
      setState(prev => ({ ...prev, loading: true, error: null }));

      try {
        const response = await fetch(url, {
          ...optionsRef.current,
          signal: abortController.signal,
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        setState({ data, error: null, loading: false });
      } catch (err) {
        if (err.name !== 'AbortError') {
          setState({ data: null, error: err, loading: false });
        }
      }
    }

    fetchData();

    return () => abortController.abort();
  }, [url]);

  return state;
}

// Usage
function UserProfile({ userId }) {
  const { data: user, error, loading } = useApi(`/api/users/${userId}`);

  if (loading) return <Skeleton />;
  if (error) return <ErrorBanner error={error} />;
  return <ProfileCard user={user} />;
}

What the interviewer wants to hear: abort in the cleanup, so a fast-changing url cannot let an old response overwrite a newer one, and unmounting cancels the request. Ignore AbortError. Treat non-2xx responses as errors, because fetch only rejects on network failure. Do not depend on options, which is a new object every render (the ref avoids that). One small wart is that optionsRef.current = options writes a ref during render, which the Rules of React advise against. Updating it inside a useLayoutEffect, or using useEffectEvent in 19.2+, is the stricter version. A refetch is easy to add with a counter in state that is included in the dependencies.

Common wrong answer / trap: No abort and no ignore flag, which gives the response race. Also useEffect(async () => ...): an async function returns a promise, and React expects the return value to be a cleanup function, so React warns.

Follow-up: "Would you ship this?" For production, use TanStack Query, SWR or your framework's loader. They provide caching, deduplication, retries, revalidation on focus, and SSR hydration. A hand-rolled hook refetches on every mount, and every component that uses it makes its own request.

Q: Write a useDebounce hook

function useDebounce(value, delay) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);

  return debouncedValue;
}

// Usage
function Search() {
  const [query, setQuery] = useState('');
  const debouncedQuery = useDebounce(query, 300);

  useEffect(() => {
    if (debouncedQuery) {
      searchApi(debouncedQuery).then(setResults);
    }
  }, [debouncedQuery]);

  return <input value={query} onChange={e => setQuery(e.target.value)} />;
}

The cleanup does the work: every new value clears the previous timer, so the state only updates once value has stayed the same for delay ms. The usage example still has the response race (an old search can resolve after a newer one). Add an ignore flag or AbortController in that effect. Sometimes you want a debounced callback instead of a debounced value, for example "save 1 s after the last edit":

function useDebouncedCallback(fn, delay) {
  const fnRef = useRef(fn);
  useLayoutEffect(() => { fnRef.current = fn; });      // always call the latest fn
  const timer = useRef();
  useEffect(() => () => clearTimeout(timer.current), []); // clear on unmount
  return useCallback((...args) => {
    clearTimeout(timer.current);
    timer.current = setTimeout(() => fnRef.current(...args), delay);
  }, [delay]);
}

Common wrong answer / trap: const debounced = debounce(fn, 300) in the component body. A new debounced function is created every render, each with its own timer, so nothing is actually debounced. A second trap: no clear on unmount, so setState fires after the component is gone.

Follow-up: "Debounce or useDeferredValue here?" Debounce, because the goal is fewer network calls. useDeferredValue keeps rendering responsive but does not reduce requests.

Q: Build infinite scroll

Put a sentinel element after the list and watch it with an IntersectionObserver. When it comes into view, load the next page. Guard against double loads, stop when there are no more pages, and disconnect the observer in the cleanup. Use cursor-based pagination on the API (not offsets), so new inserts do not cause duplicates.

import { useEffect, useRef, useState, useCallback } from 'react';

export function Feed({ fetchPage }) {           // fetchPage(cursor) → { items, nextCursor }
  const [items, setItems] = useState([]);
  const [cursor, setCursor] = useState(null);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const sentinelRef = useRef(null);
  const loadingRef = useRef(false);              // sync guard; state updates lag a render

  const loadMore = useCallback(async () => {
    if (loadingRef.current || !hasMore) return;
    loadingRef.current = true; setLoading(true);
    try {
      const { items: next, nextCursor } = await fetchPage(cursor);
      setItems(prev => [...prev, ...next]);
      setCursor(nextCursor);
      setHasMore(nextCursor != null);
    } finally {
      loadingRef.current = false; setLoading(false);
    }
  }, [cursor, hasMore, fetchPage]);

  useEffect(() => {
    const node = sentinelRef.current;
    if (!node) return;
    const io = new IntersectionObserver(
      entries => { if (entries[0].isIntersecting) loadMore(); },
      { rootMargin: '400px' }                    // prefetch before the user hits bottom
    );
    io.observe(node);
    return () => io.disconnect();
  }, [loadMore]);

  return (
    <>
      <ul>{items.map(i => <li key={i.id}>{i.title}</li>)}</ul>
      {hasMore ? <div ref={sentinelRef} aria-hidden="true" /> : <p>No more posts</p>}
      {loading && <p role="status">Loading…</p>}
      {hasMore && <button onClick={loadMore} disabled={loading}>Load more</button>}
    </>
  );
}

Common wrong answer / trap: A scroll listener that calls getBoundingClientRect on every event. It runs on the main thread, causes layout thrashing, and is easy to get wrong. Relying only on loading state as the guard is another trap, because two intersection events in the same frame both see false. That is why the code also uses a ref guard.

Follow-up: "What breaks at 10,000 items?" The DOM size. Combine infinite scroll with virtualization (next question). Also restore the scroll position on back navigation, and keep the visible "Load more" button for keyboard and screen-reader users, as above.

Q: Sketch a virtualized list

Virtualization renders only the rows in or near the viewport. The rows sit inside a container whose height equals the full list, offset by start * rowHeight. For fixed row heights the maths is just arithmetic:

// Run with node — the core of every fixed-height virtualizer.
function getVisibleRange({ scrollTop, viewportHeight, rowHeight, count, overscan = 3 }) {
  const first = Math.floor(scrollTop / rowHeight);
  const visible = Math.ceil(viewportHeight / rowHeight);
  const start = Math.max(0, first - overscan);
  const end = Math.min(count, first + visible + overscan);
  return { start, end, offsetY: start * rowHeight, totalHeight: count * rowHeight };
}
console.log(getVisibleRange({ scrollTop: 0, viewportHeight: 400, rowHeight: 40, count: 10000 }));
// { start: 0, end: 13, offsetY: 0, totalHeight: 400000 }
console.log(getVisibleRange({ scrollTop: 4000, viewportHeight: 400, rowHeight: 40, count: 10000 }));
// { start: 97, end: 113, offsetY: 3880, totalHeight: 400000 }
console.log(getVisibleRange({ scrollTop: 399800, viewportHeight: 400, rowHeight: 40, count: 10000 }));
// { start: 9992, end: 10000, offsetY: 399680, totalHeight: 400000 }
import { useState } from 'react';

export function VirtualList({ items, rowHeight = 40, height = 400, renderRow }) {
  const [scrollTop, setScrollTop] = useState(0);
  const { start, end, offsetY, totalHeight } = getVisibleRange({
    scrollTop, viewportHeight: height, rowHeight, count: items.length,
  });

  return (
    <div style={{ height, overflowY: 'auto' }} onScroll={e => setScrollTop(e.currentTarget.scrollTop)}>
      <div style={{ height: totalHeight, position: 'relative' }}>
        <div style={{ transform: `translateY(${offsetY}px)` }}>
          {items.slice(start, end).map((item, i) => (
            <div key={item.id} style={{ height: rowHeight }}>{renderRow(item, start + i)}</div>
          ))}
        </div>
      </div>
    </div>
  );
}

About 16 rows are mounted instead of 10,000, so mount time and memory stay flat whatever the list length. Overscan renders a few extra rows so fast scrolling does not show blank gaps.

Common wrong answer / trap: Keying rows by their slice index. As you scroll, every row then gets a new item, and row state ends up on the wrong data. Key by item.id. Also, virtualization breaks Ctrl+F browser search, and screen readers only see the rendered rows. Set aria-rowcount and aria-rowindex, or offer a non-virtualized fallback.

Follow-up: "Variable row heights?" Measure rows as they render (a ResizeObserver per row), cache the measured heights, keep a prefix-sum array of offsets, and binary-search it to find start for a given scrollTop. Before rows are measured, use estimated heights. This is what TanStack Virtual does. In production, use TanStack Virtual or react-window rather than your own. For simple cases, the CSS content-visibility: auto may be enough.


Staff: Server Components, Streaming and Hydration

Q: What is the difference between RSC and SSR?

AspectSSR (Server-Side Rendering)React Server Components
What runs on serverFull component tree, once, to produce HTMLServer Components only — they never ship to client
JavaScript shippedFull React app (hydration)Only Client Component code
InteractivityAfter hydration (full React bundle)Client Components are interactive immediately
Data fetchinggetServerSideProps or fetch during renderasync components with direct DB/API access
Re-rendersClient-side after hydrationServer Components re-render on server, stream updated UI
Bundle sizeEverything in the bundleServer-only code never reaches the client

Correction (2026-11-09): "Client Components are interactive immediately" (in the table and in the diagram below) is wrong. In an RSC app, Client Components are still server-rendered to HTML and still hydrate before they respond to events. RSC and SSR are complementary, not alternatives: frameworks such as Next.js App Router run both. What RSC changes is how much hydrates. Server Component code is never sent to the browser and is never hydrated. Only the Client Component islands are, and with streaming plus selective hydration they hydrate per Suspense boundary, prioritising the ones the user interacts with.

graph TD
    subgraph "SSR Flow"
        S1["Server renders HTML"] --> S2["Send HTML to browser"]
        S2 --> S3["Browser shows HTML (non-interactive)"]
        S3 --> S4["Download React bundle"]
        S4 --> S5["Hydrate — attach event listeners"]
        S5 --> S6["Interactive"]
    end

    subgraph "RSC Flow"
        R1["Server renders Server Components"]
        R2["Client Components bundled separately"]
        R1 --> R3["Stream RSC payload + Client Component JS"]
        R3 --> R4["Browser renders both"]
        R4 --> R5["Client Components interactive immediately"]
    end

    style S4 fill:#dc2626,color:#fff
    style R5 fill:#059669,color:#fff

(Per the correction above, read R5 as "Client Components interactive once hydrated, boundary by boundary".)

// Server Component (default in Next.js App Router)
// Runs on server only — never shipped to client
async function ProductPage({ id }) {
  const product = await db.query('SELECT * FROM products WHERE id = $1', [id]);
  // Can use server-only APIs, secrets, databases

  return (
    <div>
      <h1>{product.name}</h1>
      <p>{product.description}</p>
      <AddToCartButton productId={id} /> {/* Client Component */}
    </div>
  );
}

// Client Component — must opt in with 'use client'
'use client';

function AddToCartButton({ productId }) {
  const [added, setAdded] = useState(false);

  return (
    <button onClick={() => {
      addToCart(productId);
      setAdded(true);
    }}>
      {added ? 'Added' : 'Add to Cart'}
    </button>
  );
}

Correction (2026-11-09): The example above puts 'use client' in the middle of a file for brevity. It would not work: the directive has to be the first statement of its own module (only comments may come before it), and it marks that module and everything it imports as client code. In practice AddToCartButton lives in AddToCartButton.jsx, which starts with 'use client', and the Server Component imports it.

Common wrong answer / trap: "Server Components replace SSR" or "RSC means no JavaScript." There is still the React runtime and the Client Components. Another wrong idea: "Server Components are rendered on every request." With static rendering they can run at build time.

Follow-up: "What is the RSC payload?" A streamed, serialised description of the rendered Server Component tree. It contains elements, the props passed to Client Components, and references to Client Component modules. The client uses it to reconcile the tree, so a navigation can update server-rendered UI without a full reload and without losing client state.

Q: Where do you put the 'use client' boundary, and what can cross it?

'use client' marks a module boundary: that file and everything it imports end up in the client bundle. Put the boundary as low in the tree as possible (the button, not the page) to keep the bundle small. Props that cross from server to client must be serialisable: primitives, plain objects and arrays, Date, Map, Set, typed arrays, promises, JSX, and Server Functions. Ordinary functions, class instances and symbols that are not globally registered cannot cross.

// Server Component — passes a server-rendered subtree INTO a client component as children
import Tabs from './Tabs.client';          // 'use client' at the top of that file
import { ProductSpecs } from './ProductSpecs'; // stays a Server Component

export default async function Page() {
  const specs = await getSpecs();
  return (
    <Tabs labels={['Specs', 'Reviews']}>
      <ProductSpecs specs={specs} />         {/* rendered on the server, slotted into client UI */}
      <Reviews />
    </Tabs>
  );
}

A Client Component cannot import a Server Component, but it can receive one as children or another prop. This "donut" pattern keeps interactive shells thin. Use the server-only package to make the build fail if a secrets module is ever imported into client code.

Common wrong answer / trap: "A Client Component's children are client code." Not when they come from a Server Component as props: they were already rendered on the server. Another trap is passing an onClick from a Server Component. Functions cannot be serialised, and the build fails.

Follow-up: "How do you share data between Server Components without prop drilling?" Context does not work in Server Components. Call the data function again, wrapped in cache() so it is deduplicated within one request.

Q: What are Server Functions ('use server'), and what are the security implications?

A function marked with 'use server' runs on the server but can be called from the client. The bundler replaces it with a reference, and calling it sends a POST request. Used as a <form action>, it works even before JavaScript loads. Every Server Function is effectively a public HTTP endpoint.

// actions.js
'use server';
import { z } from 'zod';

const Schema = z.object({ postId: z.string().uuid(), text: z.string().min(1).max(2000) });

export async function addComment(prevState, formData) {
  const session = await getSession();                    // 1. authenticate
  if (!session) return { error: 'Sign in first' };
  const parsed = Schema.safeParse(Object.fromEntries(formData)); // 2. validate
  if (!parsed.success) return { error: 'Invalid input' };
  if (!(await canComment(session.user, parsed.data.postId)))     // 3. authorise
    return { error: 'Forbidden' };
  await db.comment.create({ data: { ...parsed.data, authorId: session.user.id } });
  revalidatePath(`/posts/${parsed.data.postId}`);        // framework API (Next.js)
  return { error: null };
}

Common wrong answer / trap: "It's only called from my component, so the inputs are safe." Anyone can call it with any payload. Validate and authorise inside every Server Function, never trust IDs from the client, and do not let closed-over values carry secrets. (Frameworks encrypt closure variables, but you should still keep secrets out of them.) The protocol layer is attack surface too. CVE-2025-55182, disclosed 3 December 2025 and nicknamed "React2Shell", was an unauthenticated remote code execution bug (CVSS 10.0) in how react-server-dom-* decoded Server Function payloads. It affected any app with RSC support, even apps that defined no Server Functions, and was fixed in 19.0.1, 19.1.2 and 19.2.1. Keep React and the framework patched.

Follow-up: "Server Functions for data fetching?" They are not recommended. They are designed for mutations, run one at a time on the client, and are not cached. Fetch in Server Components instead.

Q: How do streaming SSR and Suspense work together?

With renderToPipeableStream (Node) or renderToReadableStream (Web Streams), React sends the HTML shell straight away. Every <Suspense> boundary that is not ready yet sends its fallback. When the boundary's data resolves, React streams the finished HTML along with a small inline script that swaps it into place, even before any JavaScript bundle has loaded. Selective hydration then hydrates boundaries independently, and if the user clicks a boundary that has not hydrated yet, React hydrates that one first.

import { renderToPipeableStream } from 'react-dom/server';

app.get('*', (req, res) => {
  const { pipe, abort } = renderToPipeableStream(<App url={req.url} />, {
    bootstrapScripts: ['/client.js'],
    onShellReady() { res.setHeader('content-type', 'text/html'); pipe(res); }, // stream ASAP
    onShellError(err) { res.statusCode = 500; res.end('<h1>Error</h1>'); },
    onError(err) { console.error(err); },
  });
  setTimeout(abort, 10_000); // give up on slow boundaries; client will render them
});

The design question is where the boundaries go. Too few, and the slowest query holds back the whole page. Too many, and the page fills in piece by piece with layout shift. Group content that should appear together, and give fallbacks the same size as the final content. React 19.2 also batches reveals of server-rendered boundaries for a short time, to reduce this flicker.

Common wrong answer / trap: Putting data fetching at the top of the page (await everything in the root), which removes streaming entirely. Another trap: setting the status code or headers after pipe() has started. Once streaming begins the status is committed, so a "not found" deep in the tree needs to be detected before the shell is sent, or handled on the client.

Follow-up: "What about SEO bots?" Use onAllReady instead of onShellReady for crawlers, so they receive the complete HTML.

Q: What causes hydration mismatches and how do you fix them?

Hydration attaches React to server-rendered HTML and expects the first client render to produce exactly the same markup. Common causes: Date.now(), Math.random() or new Date().toLocaleString() during render; reading window or localStorage during render; locale or timezone differences; invalid HTML nesting (<div> inside <p>, which the browser's parser rearranges); and browser extensions that inject attributes. React 19 reports a single diff of the mismatch instead of many vague errors. For a text mismatch it falls back to client rendering up to the nearest Suspense boundary.

// BAD — server and client disagree
function Clock() { return <span>{new Date().toLocaleTimeString()}</span>; }

// GOOD — render a stable value first, update after hydration
function Clock() {
  const [time, setTime] = useState(null);
  useEffect(() => {
    setTime(new Date().toLocaleTimeString());
    const id = setInterval(() => setTime(new Date().toLocaleTimeString()), 1000);
    return () => clearInterval(id);
  }, []);
  return <span>{time ?? '--:--:--'}</span>;
}

// For one unavoidable text difference (e.g. a timestamp):
<time suppressHydrationWarning>{new Date().toISOString()}</time>

Common wrong answer / trap: Adding suppressHydrationWarning everywhere. It only works one level deep, on text and attributes, and it hides real bugs. Another trap: typeof window !== 'undefined' ? A : B in render. That is the very thing that causes a mismatch.

Follow-up: "Why do IDs from useId match but Math.random() ids don't?" useId is derived from the component's position in the tree, which is the same on server and client.

Staff: Compiler, Performance and Architecture

Q: What is the React Compiler and what changes when you adopt it?

React Compiler (stable 1.0 since 7 October 2025) is a build-time tool, currently a Babel plugin (babel-plugin-react-compiler), that memoises components and hooks automatically. It analyses data flow and mutability, then caches JSX, computed values and callbacks at a finer grain than hand-written useMemo allows, including after early returns. It works with React 17 and later; on 17 and 18 you set target and add react-compiler-runtime. Meta reported up to 12% faster initial loads and navigations, and some interactions more than 2.5× faster, on the Quest Store.

// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react({ babel: { plugins: ['babel-plugin-react-compiler'] } })],
});
// You write this…
function TodoList({ todos, filter }) {
  const visible = todos.filter(t => t.status === filter);
  return <List items={visible} onSelect={id => select(id)} />;
}
// …and the compiler caches `visible`, the arrow function and the <List> element,
// recomputing them only when `todos` or `filter` change.

The compiler assumes your code follows the Rules of React: pure render, no mutating props or state, hooks at the top level. Components that break the rules are skipped, or can behave differently. The compiler-powered lint rules now ship in eslint-plugin-react-hooks (recommended preset), so turn them on first.

Common wrong answer / trap: "Delete every useMemo once the compiler is on." The React team advises leaving existing memoisation alone, or removing it only with careful testing, because effect dependencies may change. Also pin an exact compiler version if test coverage is thin. A second trap: assuming the compiler fixes expensive algorithms or excessive DOM size. It removes needless re-renders, and nothing else.

Follow-up: "How do you opt a component out?" Add the 'use no memo' directive at the top of the function, then fix the rule violation it was working around.

Q: How do you profile and fix a slow React app?

Measure first, using field data where possible. A good workflow:

  1. Reproduce with CPU throttling (4x–6x) in a production build. Development builds are several times slower and mislead you.
  2. React DevTools Profiler: record the interaction and read the flamegraph for long commits. "Why did this render?" names the changed props, state, hooks or context.
  3. Chrome Performance panel: since React 19.2 it has React Performance Tracks (Scheduler and Components), which show long tasks, layout, and whether React or your own code is the cost.
  4. Classify the cost. Too many components rendering → move state down, split contexts, use selectors, memo or the compiler. One component too slow → useMemo, a better algorithm, a Web Worker. Too many DOM nodes → virtualization. Input lag → useTransition or useDeferredValue. Slow load → code splitting, RSC, streaming.
  5. Verify with numbers. Measure INP, LCP and CLS with the web-vitals library in production. INP is the metric that reflects re-render cost.
import { Profiler } from 'react';

function onRender(id, phase, actualDuration, baseDuration) {
  // actualDuration: time spent rendering this commit; baseDuration: estimated cost without memoisation
  if (actualDuration > 16) console.warn(`${id} ${phase} took ${actualDuration.toFixed(1)}ms`);
}

export default function App() {
  return (
    <Profiler id="Dashboard" onRender={onRender}>
      <Dashboard />
    </Profiler>
  );
}

Common wrong answer / trap: "Add memo everywhere and measure later." Or profiling in development mode. Or optimising render counts when the real cost is a 4 MB bundle or a request waterfall.

Follow-up: "What's a typical big win?" Fixing a context or global store that re-renders the whole tree on every keystroke, or virtualizing a 5,000-row table. Each regularly cuts interaction time by an order of magnitude.


Quick-Fire Questions

QuestionAnswer
What is StrictMode?Development-only wrapper that double-invokes render and effects to surface bugs. No production impact.
Controlled vs uncontrolled components?Controlled: React state drives the input (value + onChange). Uncontrolled: DOM holds the state (ref).
What is a portal?ReactDOM.createPortal(child, domNode) — renders children into a DOM node outside the parent hierarchy. Used for modals, tooltips.
What is useId?Generates stable unique IDs for accessibility attributes. Works with SSR (avoids hydration mismatches).
useLayoutEffect vs useEffect?useLayoutEffect fires synchronously after DOM mutations, before paint. Use for DOM measurements. useEffect fires asynchronously after paint. (Usually. See the correction in the useLayoutEffect question: effects caused by discrete input can flush before paint.)
What is useTransition?Marks state updates as non-urgent. React keeps the old UI visible while rendering the new one, preventing janky loading states.
useDeferredValue?Returns a deferred version of a value. React renders with the old value first, then re-renders with the new value at lower priority.
What is forwardRef?Passes a ref through a component to a child DOM element. Required because function components do not have instances. Correction (2026-11-09): that was true before React 19. Since 19, function components receive ref as a normal prop, and forwardRef is slated for deprecation.
Do portals bubble events?Yes, through the React tree, not the DOM tree. A click in a modal portal reaches onClick handlers on its React ancestors.
<Activity> (19.2)?<Activity mode="hidden"> keeps a subtree's state but unmounts its effects and defers its updates, for example pre-rendering the next tab or keeping a hidden tab's state.
Document metadata in React 19?<title>, <meta> and <link> rendered anywhere are hoisted into <head>. Stylesheets with precedence are deduplicated and ordered.
cache()?RSC-only per-request memoisation of a data function. cacheSignal() (19.2) tells you when that cache lifetime ends so you can abort work.
Class components still needed?Only for error boundaries. Everything else has a hook equivalent.