React Internals: Rendering, Effects, Errors, and Concurrency
System DesignModel answerLast updated
Walk through how React reconciles trees, when effects run, how to contain component failures, and what concurrent mode primitives actually buy you.
React Under the Hood
A solid grasp of React goes beyond knowing the hook names. The questions below probe why the library behaves the way it does and how to design around its failure modes.
1. Tree Diffing and Keys
React compares the previous render tree against the new one before touching the real DOM. Explain how that comparison works, what role the key prop plays, and what goes wrong when keys are unstable — for example, when you use an array index on a list that can be reordered or filtered.
2. useEffect and Dependency Tracking
Describe the difference between passing a list of variables to useEffect and passing an empty array []. When does React decide to call the cleanup function returned by an effect? What misconceptions do developers commonly hold about these behaviors?
3. Containing Failures in a Large UI
You are building a dashboard where dozens of independent widgets share the same page. A bug in one widget must not blank the entire screen.
- Explain how Error Boundaries intercept failures and where their limits are (for example, why they don't catch errors thrown in a button's click handler).
- Show how you would handle an error that surfaces inside an
asyncfunction triggered by user interaction — both when the error is recoverable and when it should hand off to the nearest boundary.
4. Keeping the UI Responsive in React 18
React 18 introduced useTransition and useDeferredValue. Explain what class of problem each one solves, how they differ from each other, and when you would reach for one over the other.
For each topic, go beyond definitions: name the concrete failure mode the concept exists to prevent and what you would actually do about it.
Hints
Hint 1
For the diffing question, think about what React assumes when it sees two elements of the same type at the same position — and what it can't know without a key.
Hint 2
For effects, trace what happens step by step when a dependency changes: which callback runs first, and which values does it close over?
Hint 3
For async error handling, Error Boundaries only catch errors that surface during React's render or commit phase — so ask yourself: how could you get an async error back into that phase intentionally?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. How React Diffs Trees and Why Keys Matter
Every render produces a lightweight JavaScript object tree. React walks the new tree and the previous one side by side to figure out the minimum set of real DOM mutations needed. This is reconciliation.
An exact tree diff is O(n³), which is too slow at scale. React uses an O(n) heuristic built on two rules.
Different element types → full remount. If a node changes from <div> to <section>, or from <UserCard> to <AdminCard>, React tears down the old subtree entirely — destroying any local state it held — and mounts a fresh one.
Same element type → update in place. For DOM nodes, React patches changed attributes. For components, it keeps the existing instance and its state and passes new props. It then recurses into the children.
The key prop gives React a stable identity it can use when matching children across renders. Without keys, children are matched by position. Inserting a row at the top of a list shifts every position by one, so React sees every item as "changed" and re-renders the whole list. A stable key lets React see "this item just moved" and reuse it.
Unstable keys break identity. Using the array index as a key on a list that can reorder, filter, or grow at the front means item B might now sit at index 0. React reuses the component slot that previously held item A, so any local state, controlled-input value, focus state, or animation attached to that slot now belongs to the wrong row. Using Math.random() as a key is worse — every item remounts on every render, destroying all state and hurting performance. Use a stable ID from your data.
// good — stable identity
{todos.map(t => <TodoItem key={t.id} todo={t} />)}
// breaks on reorder — position isn't identity
{todos.map((t, i) => <TodoItem key={i} todo={t} />)}
One useful corollary: you can force a remount deliberately by changing a key. <ProfileForm key={userId} /> resets the whole form when the user switches accounts.
2. useEffect Dependencies and Cleanup
Effects run after React commits the updated DOM to the browser.
| Dependency argument | When the effect fires |
|---|---|
| Omitted | After every render |
[] | Once after the initial mount; cleanup on unmount |
[a, b] | After mount, then after any render where a or b changed (compared with Object.is) |
Cleanup timing. React holds the cleanup from the last effect run. It calls that cleanup right before running the effect again, and again on unmount. Critically, the cleanup closes over the previous render's values, not the current ones — which is exactly what you need to cancel stale work:
useEffect(() => {
const ctrl = new AbortController();
fetch(`/api/user/${id}`, { signal: ctrl.signal })
.then(r => r.json())
.then(setUser)
.catch(e => { if (e.name !== 'AbortError') setError(e); });
return () => ctrl.abort(); // cancels in-flight request when id changes
}, [id]);
Common mistakes interviewers probe:
- Treating
[]as "run once." It means "this effect has no dependencies." If you use a variable inside the effect but leave it out of the array, you get a stale closure — the effect reads a value that never updates. - Putting objects or functions created during render into the array. They are recreated every render, so the effect runs every render. Either move them inside the effect or memoize them.
- StrictMode double-invocation. In development, React mounts, unmounts, and remounts every component to surface missing cleanups. This is intentional, not a bug.
3. Error Containment Architecture
How Error Boundaries work. An Error Boundary is a class component that implements static getDerivedStateFromError (which switches to fallback UI during render) and/or componentDidCatch (which fires at commit time and is where you log to Sentry or similar). When a descendant throws during rendering, a lifecycle, or a constructor, React unwinds to the nearest boundary and renders its fallback in place of that subtree. Everything outside the boundary keeps working.
For a dashboard, wrap each widget independently so one broken chart shows "Widget unavailable" while the rest of the page stays functional. Keep one boundary at the root as a final backstop.
<ErrorBoundary fallback={<WidgetError />} key={retryCount}>
<RevenueChart />
</ErrorBoundary>
What boundaries cannot catch: errors in event handlers, async code (setTimeout, promise callbacks, await continuations), server-side rendering, and errors thrown by the boundary itself.
Why not event handlers? They run outside React's render cycle. React doesn't need to know about them to decide what UI to display, so it never wraps them in a try/catch.
Async errors from user interaction. Catch them yourself, then decide what to do:
const [, forceError] = useState();
async function handleSave() {
try {
setStatus('saving');
await api.save(formData);
setStatus('saved');
} catch (err) {
// Recoverable (e.g., validation failure, 409 conflict): show inline message
setError(err.message);
// Fatal for this widget: re-throw into render so the boundary catches it
// forceError(() => { throw err; });
}
}
The forceError trick works because a state updater that throws surfaces the error during React's next render, landing it in the nearest boundary. The react-error-boundary library wraps this as showBoundary(err). Add window.addEventListener('unhandledrejection', ...) at the app root to catch anything that slips through both paths.
4. Concurrency Primitives: useTransition and useDeferredValue
React 18 made rendering interruptible. Updates can now be marked urgent or non-urgent. Urgent updates (typing, clicking) must feel instant. Non-urgent updates (filtering a large table, switching a heavy tab) can be interrupted if something more urgent arrives.
useTransition — use when you control the state setter.
const [isPending, startTransition] = useTransition();
function handleChange(e) {
setInputValue(e.target.value); // urgent: input stays live
startTransition(() => setFilterQuery(e.target.value)); // low-priority, interruptible
}
If the user types again before the transition finishes, React discards the stale render and restarts. isPending lets you dim stale content or show a subtle spinner. With Suspense, a pending transition holds the existing UI on screen instead of flashing a loading fallback.
useDeferredValue — use when you receive a value from outside (a prop, for example) and don't own its setter.
const deferredQuery = useDeferredValue(query);
const results = useMemo(
() => filterRows(allRows, deferredQuery),
[allRows, deferredQuery]
);
React renders with the old deferred value first (keeping the UI responsive), then schedules a low-priority re-render with the new value when it has time.
Choosing between them: reach for useTransition when you own the state update; reach for useDeferredValue when you're downstream of someone else's update. Neither replaces virtualization or memoization for genuinely expensive work — they just make the lag feel less blocking.