Situational React questions rarely ask what a hook does. They describe a bug in a running product and expect you to name the mechanism behind it. Examples include a list that shows the wrong input after a delete, a dashboard that flashes stale data, a search box that stutters, or a page that logs hydration warnings. This guide covers the mechanisms that explain most of those bugs. You will see how React decides what to keep and what to throw away, how effects interact with time, and where state should live. It also covers when memoization helps, how concurrent features keep input responsive, and how to contain failures, ship less JavaScript and render on the server without mismatches. Each concept comes with a small invented scenario, code you can run, and the traps interviewers like to probe.
Study order
If time is short, go in this order.
- Effects, cleanup and race conditions
Effect misuse causes the most common production bugs, such as stale data, leaks and double requests, and interviewers probe it constantly.
- Where state lives and what should not be state
Most re-render and sync bugs trace back to duplicated or misplaced state, so this shapes every other answer you give.
- Keys, component identity and reconciliation
Understanding identity explains lost state, remounts and list bugs, and it is the basis for reasoning about performance.
- Re-renders, memoization and measuring first
Senior candidates are expected to diagnose slow renders with measurements and explain referential equality precisely.
- Error boundaries and failure containment
Resilience questions are a staple of senior interviews, and knowing exactly what boundaries do not catch sets candidates apart.
- Code splitting with lazy and Suspense
Bundle size directly affects load performance, and good split points plus failure handling show production experience.
- Concurrent rendering: transitions and deferred values
Modern React's answer to input lag. You need to explain what it does and, just as important, what it does not do.
- Server rendering and hydration mismatches
Essential if the role uses a server-rendering framework, and hydration mismatches are a frequent real-world debugging story.
Keys, component identity and reconciliation
On every render React compares the new element tree with the previous one. If an element has the same type in the same position, React keeps the component instance and its state and only updates props. If the type changes, React unmounts the old subtree and mounts a new one, and all state inside it is lost. In lists, the key prop replaces position as the identity, so React can match items that moved, were inserted or were deleted.
Take the invoice editor in a billing app called Ledgerly. Each line has an uncontrolled text input. If the lines are keyed by array index and the user removes line 2 of 5, the item at index 2 is now what used to be line 3. React keeps the DOM input for index 2, so the typed text stays in place while the data underneath it shifts. A stable key such as a database id ties the DOM and state to the record, not to the slot.
You can also use keys deliberately. Rendering <CustomerForm key={customerId} /> throws away the form state whenever the customer changes. That is cleaner than an effect that resets several fields by hand.
TypeScript
import { useState } from 'react';
type Line = { id: string; label: string };
export function InvoiceLines({ initial }: { initial: Line[] }) {
const [lines, setLines] = useState(initial);
const remove = (id: string) => setLines((prev) => prev.filter((l) => l.id !== id));
return (
<ul>
{lines.map((line) => (
// Stable id: the input's DOM node and text follow the record
<li key={line.id}>
<input defaultValue={line.label} />
<button onClick={() => remove(line.id)}>Remove</button>
</li>
))}
</ul>
);
}With key={index}, removing a line would leave the typed text on the wrong row.
Traps
- Using the array index as a key for lists that can be reordered, filtered or have items removed. Index keys are only safe for static lists.
- Generating keys during render with
Math.random()orcrypto.randomUUID(). Every render then creates new identities, so React remounts every row and wipes its state. - Defining a component inside another component's body. Each render creates a new function, so React sees a new type and remounts the whole subtree, losing focus and state.
- Writing an effect that resets local state when an id prop changes, when a
keyon the component would do it in one line without the extra render.
Effects, cleanup and race conditions
useEffect is for synchronising a component with something outside React, such as a network request, a subscription, a timer or a third-party widget. The rule that prevents most production bugs is simple. Every effect that starts something must return a cleanup that stops it. React runs the cleanup before the effect runs again with new dependencies, and when the component unmounts.
Picture the flight board in an airport app called Gatewise. A user clicks flight BA12 and then quickly clicks LH400. Both requests are in flight. If BA12 responds last, a naive effect writes BA12's status under the LH400 heading. To fix it, abort the previous request in cleanup with an AbortController, or set an ignore flag that the stale response checks before calling setState.
In development, Strict Mode mounts each component, unmounts it and mounts it again. As a result, every effect runs, cleans up and runs again. This is deliberate, because it exposes effects with missing cleanup. The right answer in an interview is to make the effect idempotent with proper cleanup, not to disable Strict Mode.
TypeScript
import { useEffect, useState } from 'react';
export function FlightStatus({ flightId }: { flightId: string }) {
const [status, setStatus] = useState<string | null>(null);
useEffect(() => {
const controller = new AbortController();
setStatus(null);
fetch(`/api/flights/${flightId}`, { signal: controller.signal })
.then((res) => res.json())
.then((data: { status: string }) => setStatus(data.status))
.catch((err: unknown) => {
if (!(err instanceof DOMException && err.name === 'AbortError')) {
console.error(err);
}
});
return () => controller.abort();
}, [flightId]);
return <p>{status ?? 'Loading...'}</p>;
}Cleanup aborts the previous request, so a slow BA12 response can never overwrite LH400.
Traps
- Leaving a dependency out of the array to stop an effect from rerunning. The effect then reads stale props or state. Fix the cause instead, for example by moving the object inside the effect or using a functional state update.
- Using an effect to compute values from props or state. That adds an extra render and a frame where the screen shows inconsistent data. Compute the value during render instead.
- Putting an object or function created during render into the dependency array. Its reference changes on every render, so the effect runs on every render.
- Responding to a user action, such as submitting a payment, inside an effect that watches a flag. Do that work in the event handler that caused it.
Where state lives and what should not be state
Good state design means keeping the minimal source of truth and deriving everything else. Totals, filtered lists, validation results and labels can all be computed from existing props and state during render. If you copy them into state, you take on the job of keeping two values in sync, and sooner or later they drift apart.
Placement matters as much as shape. State should live in the lowest common owner of the components that read it. If it lives too high, every keystroke re-renders a large tree. If it lives too low, siblings end up syncing through effects. Data from the server is a different category. It has a cache, a staleness policy and refetching rules, so in production it usually belongs in a server-cache library or a framework loader, not in a hand-rolled useState plus useEffect.
Consider the orders panel in a wholesale tool called Crateline. It receives orders as props and has a single piece of UI state, a toggle for shipped orders. The visible list and the revenue figure are pure functions of those two inputs. With 20 orders, plain computation in render is fine. With 50,000 orders and a costly filter, useMemo caches the result until the inputs change.
TypeScript
import { useMemo, useState } from 'react';
type Order = { id: string; status: 'open' | 'shipped'; total: number };
export function OrdersPanel({ orders }: { orders: Order[] }) {
const [showShipped, setShowShipped] = useState(false);
// Derived, not stored: always consistent with props
const visible = useMemo(
() => orders.filter((o) => showShipped || o.status === 'open'),
[orders, showShipped]
);
const revenue = visible.reduce((sum, o) => sum + o.total, 0);
return (
<section>
<label>
<input type="checkbox" checked={showShipped} onChange={(e) => setShowShipped(e.target.checked)} />
Show shipped
</label>
<p>{visible.length} orders, {revenue.toFixed(2)} total</p>
</section>
);
}No useEffect and no second useState: the list and the total cannot drift from the props.
Traps
- Initialising state from a prop with
useState(props.value)and expecting it to update later. The initial value is read only on mount. - Storing a whole selected object instead of its id. When the list refreshes, the stored object is stale. Store the id and look the object up during render.
- Putting fast-changing values such as input text or hover state in a global context. Every consumer re-renders on every change.
- Copying server responses into a global client store by hand, which reinvents caching, deduplication and invalidation without getting them right.
Re-renders, memoization and measuring first
A component re-renders when its own state changes, when its parent re-renders, or when a context it reads changes. A re-render is not a DOM update. React computes the output and only commits the differences. Most re-renders are cheap, so the real question is whether a particular one is expensive enough to matter, and the React DevTools Profiler answers that with real measurements.
memo lets a component skip rendering when its props are shallowly equal to the previous ones. That only works if the props are referentially stable. An inline arrow function or object literal is a new reference on every render, so it defeats memo completely. useCallback and useMemo exist mainly to keep those references stable, and secondarily to cache expensive calculations.
In a helpdesk app called Queuebird, typing in the reply box re-rendered 800 ticket rows. Wrapping the row in memo and making the close handler stable with useCallback limits each keystroke to the input. Often, moving the draft state into its own small component solves the same problem with no memoization at all. If your project uses the React Compiler, it inserts much of this memoization automatically, but you still need to understand referential equality to read its output and debug it.
TypeScript
import { memo, useCallback, useState } from 'react';
type Ticket = { id: number; title: string };
const TicketRow = memo(function TicketRow(props: { ticket: Ticket; onClose: (id: number) => void }) {
return (
<li>
{props.ticket.title}
<button onClick={() => props.onClose(props.ticket.id)}>Close</button>
</li>
);
});
export function TicketBoard({ initial }: { initial: Ticket[] }) {
const [tickets, setTickets] = useState(initial);
const [draft, setDraft] = useState('');
const handleClose = useCallback((id: number) => {
setTickets((prev) => prev.filter((t) => t.id !== id));
}, []);
return (
<>
<input value={draft} onChange={(e) => setDraft(e.target.value)} />
<ul>
{tickets.map((t) => (
<TicketRow key={t.id} ticket={t} onClose={handleClose} />
))}
</ul>
</>
);
}The functional update lets handleClose have empty dependencies, so its reference never changes.
Traps
- Wrapping a component in
memowhile passing itstyle={{...}}or an inline callback. The comparison fails on every render and you pay its cost for nothing. - Adding
useMemoeverywhere by default. It adds memory use, dependency bugs and noise. Profile first and memoize the hot paths. - Assuming
memoblocks context updates. A memoized component still re-renders when a context it consumes changes. - Mutating an array or object in place and calling
setStatewith the same reference. React bails out of the update, so the UI never changes.
Concurrent rendering: transitions and deferred values
Since React 18, React can work on a render, pause it to handle a more urgent update, and throw away work that is no longer needed. You opt in by marking updates as non-urgent. startTransition (or useTransition, which also gives you an isPending flag) wraps a state update you control. useDeferredValue gives you a lagging copy of a value when you do not control the update that produces it.
The parts catalogue in a repair-shop app called Wrenchly filters 5,000 part names on every keystroke. The text input must update instantly. The table can trail behind. With useDeferredValue, React first renders with the old query, which keeps typing smooth, and then renders the table with the new query in the background. If another key arrives first, React abandons that background render.
This does not make the filtering itself faster. It keeps the expensive work from blocking input. The deferred subtree also has to be memoized, or it re-renders with the urgent update anyway. Transitions also tell Suspense to keep showing the existing content rather than falling back to a spinner when the new content suspends.
TypeScript
import { memo, useDeferredValue, useState } from 'react';
const PartsTable = memo(function PartsTable({ query, parts }: { query: string; parts: string[] }) {
const q = query.toLowerCase();
const rows = parts.filter((p) => p.toLowerCase().includes(q));
return <ul>{rows.map((p) => <li key={p}>{p}</li>)}</ul>;
});
export function PartsSearch({ parts }: { parts: string[] }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<PartsTable query={deferredQuery} parts={parts} />
</div>
</>
);
}The input stays responsive and the table dims while its render is behind.
Traps
- Wrapping the controlled input's own
setStatein a transition. Text input updates must be urgent, or the cursor lags and characters appear to jump. - Expecting transitions to help with heavy synchronous work outside rendering, such as parsing a large JSON payload. They only make React rendering interruptible.
- Using
useDeferredValuewithoutmemoon the expensive child, which then re-renders during the urgent pass as well. - Treating transitions as a debounce. They do not delay network requests, so you still need to handle request races and cancellation.
Error boundaries and failure containment
Without a boundary, an error thrown while rendering unmounts the entire React root and the user sees a blank page. An error boundary is a class component that implements static getDerivedStateFromError, to switch to a fallback UI, and usually componentDidCatch, to report the error. It catches errors thrown during rendering, in lifecycle methods and in effects of the components below it.
Where you place boundaries is a product decision. On an energy-trading dashboard called Gridwise, one boundary per widget means a crashed price chart shows a compact message while the order book keeps working. A top-level boundary is still worth having as a last resort. A boundary is also the natural place to send the error and the component stack to your monitoring service.
Be precise about what boundaries do not catch: errors inside event handlers, errors in asynchronous code such as a rejected promise inside setTimeout, errors during server rendering, and errors thrown in the boundary itself. Handle event handler errors with try/catch and state. To route an async error into a boundary, store it in state and throw it during the next render.
TypeScript
import { Component, type ErrorInfo, type ReactNode } from 'react';
function sendToMonitoring(error: Error, componentStack: string): void {
console.error('[monitoring]', error.message, componentStack);
}
type Props = { fallback: ReactNode; children: ReactNode };
type State = { hasError: boolean };
export class WidgetBoundary extends Component<Props, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State {
return { hasError: true };
}
componentDidCatch(error: Error, info: ErrorInfo) {
sendToMonitoring(error, info.componentStack ?? '');
}
render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}
// <WidgetBoundary fallback={<p>Price chart unavailable</p>}><PriceChart /></WidgetBoundary>One boundary per widget keeps a single crash from blanking the whole dashboard.
Traps
- Claiming boundaries catch errors from
onClickhandlers or rejected fetch promises. They do not. - Having only one root-level boundary, so any widget failure replaces the whole app with an error page.
- Offering no way to recover. Give the fallback a retry that resets the boundary state, or remount the boundary with a new
keywhen the route changes. - Trying to write a boundary as a function component. React has no hook equivalent for
getDerivedStateFromError, so use a class or a small library wrapper.
Code splitting with lazy and Suspense
Every kilobyte of JavaScript in the initial bundle has to be downloaded, parsed and executed before the page becomes interactive. lazy combined with a dynamic import() lets the bundler split a component into its own chunk, which is fetched the first time that component renders. The Suspense boundary above it shows a fallback while the chunk loads.
Good split points are routes and heavy features that most users never open. In an analytics product called Tallyhouse, the report builder pulls in a charting and spreadsheet library that most visitors never use. Loading it only when someone clicks Build report keeps it off the initial path for everyone else. You can also start the import on hover or focus, so the chunk is often ready before the click lands.
Think about where you put Suspense boundaries. One boundary around the whole app means any lazy chunk swaps the entire page for a spinner. Boundaries around regions keep the shell stable. Remember too that a failed chunk download, for example after a deploy removed old files, throws an error, so pair Suspense with an error boundary.
TypeScript
import { lazy, Suspense, useState } from 'react';
// Module-level: the lazy component is created once
const ReportBuilder = lazy(() => import('./ReportBuilder'));
const preload = () => void import('./ReportBuilder');
export function AnalyticsPage() {
const [open, setOpen] = useState(false);
return (
<>
<button onMouseEnter={preload} onClick={() => setOpen(true)}>
Build report
</button>
{open && (
<Suspense fallback={<p>Loading report builder...</p>}>
<ReportBuilder />
</Suspense>
)}
</>
);
}./ReportBuilder must have a default export. The hover preload reuses the same chunk.
Traps
- Calling
lazy()inside a component body. That creates a new component type on every render, which remounts it and loses its state. - Splitting tiny components. Each extra request adds latency, so split along routes and heavy dependencies.
- Forgetting that a chunk request can fail after a deploy. Without an error boundary and a reload or retry path, users on an old tab see a crash.
- Using
lazyon a named export without a wrapper. It expects a module with a default export, so map it with.then((m) => ({ default: m.Named })).
Server rendering and hydration mismatches
With server rendering, HTML arrives already populated, which helps first paint and SEO. Hydration then attaches React to that existing markup instead of building it from scratch. For that to work, the first client render must produce the same output as the server render. If it does not, React logs a hydration error. Depending on where the difference is, React then either patches the text or discards the server HTML for that subtree and renders it on the client, which costs you the benefit you paid for.
Common causes are values that differ between environments. These include Date.now(), Math.random(), toLocaleString() with a different server locale or time zone, reading window or localStorage during render, and invalid HTML nesting such as a div inside a p. In a field-service app called Routewise, a 'last synced' timestamp formatted in the browser's time zone did not match the server's UTC output on every page load.
The usual fix is to render something stable on the server and during the first client render, then switch to the client-only value in an effect after mount. Generate ids with useId so they match on both sides. Keep suppressHydrationWarning for a single text node you know will differ, such as a timestamp. It is not a general mute button.
TypeScript
import { useEffect, useState } from 'react';
export function LastSynced({ isoTime }: { isoTime: string }) {
// Server and first client render both output the ISO string
const [label, setLabel] = useState(isoTime);
useEffect(() => {
// Runs only in the browser, after hydration
setLabel(new Date(isoTime).toLocaleString());
}, [isoTime]);
return <time dateTime={isoTime}>{label}</time>;
}The locale-specific label appears after hydration, so server and client markup match.
Traps
- Branching on
typeof window !== 'undefined'during render. The server and the client then render different trees by design. - Reading
localStoragefor theme or auth during render, which causes mismatches and visible flicker. Use a cookie the server can read, or apply the value after mount. - Generating ids with a counter or
Math.random()for label and input pairs instead ofuseId. - Silencing every warning with
suppressHydrationWarning. It only applies one level deep and hides real bugs.
Common questions
Short answers to the usual doubts.
Do I need to know class components for a modern React interview?
Enough to read them and write an error boundary, which still requires a class. Day-to-day code uses function components and hooks, and interviewers mostly care whether you understand the lifecycle concepts those hooks replace.
How should I answer when asked how I would speed up a slow React page?
Start with measurement. Use the React DevTools Profiler for render cost and the browser performance tools for network, parsing and long tasks. Then work through the likely causes in order: state placed too high, unstable props defeating memo, large lists that need virtualisation, heavy bundles that need splitting, and expensive updates that could be deferred. Naming the measurement step first is what signals experience.
Should data fetching happen in useEffect?
It works for simple cases if you handle cleanup and races, but in production you usually want a data layer that provides caching, deduplication, retries and invalidation. That is either a server-cache library or your framework's loaders and server components. Be ready to explain the race condition that hand-written effect fetching has to handle.
Why do my effects run twice in development?
Strict Mode deliberately mounts, unmounts and mounts components again in development to expose effects without proper cleanup. It does not happen in production builds. The fix is to make the effect safe to run again with correct cleanup, not to remove Strict Mode.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- React in productionTake the test
- Cart reducer (React)Solve the exercise
- Filtered product list (derived state)Solve the exercise
- State architecture of a React back officeSolve the exercise