React.js Interview Questions
Senior React engineering guide exploring Fiber reconciliation, hook dependency graphs, concurrent rendering, batching semantics, and state management trade-offs.
Practice React.js Interview Questions
Showing 16 of 16 technical questions with engineering explanations
What is the difference between Controlled and Uncontrolled components in React forms, and when would you pick each?
Senior Engineering Answer
In a controlled component, React state is the single source of truth: the input receives its value prop from state and updates it via an onChange handler on every keystroke, enabling instant field validation, conditional formatting, or disabled submit logic. In an uncontrolled component, the DOM node owns its own value via defaultValue, and React reads it on demand using a ref or FormData on form submission, avoiding per-keystroke re-renders on large forms.
function SearchInput({ onSubmit }: { onSubmit: (q: string) => void }) {
const [query, setQuery] = useState("");
return (
<form onSubmit={(e) => { e.preventDefault(); onSubmit(query.trim()); }}>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Filter items..."
/>
</form>
);
}Switching an input between undefined and a string value (e.g., value={user.name} before user loads) triggers React's 'changing an uncontrolled input to be controlled' warning; always initialize controlled values to ''.
How does React's reconciliation use the 'key' prop, and why is using the array index as key buggy for dynamic lists?
Senior Engineering Answer
React diffs sibling lists in O(n) time by matching elements across renders using their type and key. When you use an array index as key and insert, delete, or reorder an item, all subsequent items receive different indices—so React pairs the wrong old Fiber node and DOM element with the new item data. This corrupts uncontrolled input state, focus, and CSS transitions, and forces unnecessary DOM updates. Use a stable, unique domain ID (such as item.id) instead.
{items.map((item) => (
<RowItem key={item.id} item={item} />
))}Generating 'key={Math.random()}' or 'key={crypto.randomUUID()}' inside render is even worse than index keys: every parent re-render unmounts and remounts every child component from scratch, wiping all local state.
Why does calling setCount(count + 1) three times in one handler only increment by 1, and how does automatic batching work?
Senior Engineering Answer
Each render sees a constant snapshot of state variables captured in that render's closure. Calling setCount(count + 1) three times queues three updates all reading the same snapshot value (e.g., 0 + 1). Passing an updater function—setCount((prev) => prev + 1)—queues pure state transitions that React applies sequentially to the latest pending state. Since React 18, automatic batching groups multiple state updates inside promises, setTimeout, and native event listeners into a single re-render instead of flushing after each call.
function Counter() {
const [count, setCount] = useState(0);
function incrementThree() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return <button onClick={incrementThree}>{count}</button>;
}Updater functions passed to setState must be pure (no side effects or mutations), because React StrictMode in development invokes updater functions twice to surface impurity bugs.
How does React Context work, and why can putting fast-changing state in a single Context hurt performance?
Senior Engineering Answer
React Context lets an ancestor Provider broadcast a value to any descendant calling useContext without threading props through intermediate components. However, whenever the Provider's value changes by Object.is() comparison, every consumer calling useContext re-renders unconditionally—even if the consumer only reads a single field that did not change—because Context has no built-in selector mechanism. Passing an inline object literal (<Ctx.Provider value={{ user, setUser }}>) creates a fresh reference on every parent render and re-renders all consumers.
const AuthUserContext = createContext<User | null>(null);
const AuthActionsContext = createContext<{ logout: () => void } | null>(null);
function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const actions = useMemo(() => ({ logout: () => setUser(null) }), []);
return (
<AuthActionsContext.Provider value={actions}>
<AuthUserContext.Provider value={user}>{children}</AuthUserContext.Provider>
</AuthActionsContext.Provider>
);
}Splitting read-only state and stable dispatch/action callbacks into separate Contexts prevents components that only trigger actions from re-rendering whenever state updates.
How do you prevent stale response race conditions when fetching data inside useEffect?
Senior Engineering Answer
If a user types quickly or switches tabs while an older fetch is still in flight, the slower earlier request can resolve after the newer request and overwrite fresh UI state with stale data. In the useEffect cleanup function, either abort the request with an AbortController or set a local 'let cancelled = false' flag so stale completions are ignored. In development, React StrictMode mounts, unmounts, and remounts effects specifically to verify your cleanup aborts or cleans up side effects properly.
useEffect(() => {
const controller = new AbortController();
let ignore = false;
async function loadProfile() {
try {
const res = await fetch(`/api/users/${userId}`, { signal: controller.signal });
const data = await res.json();
if (!ignore) setProfile(data);
} catch (err) {
if ((err as Error).name !== "AbortError") setError(err as Error);
}
}
loadProfile();
return () => {
ignore = true;
controller.abort();
};
}, [userId]);Omitting a dependency from the useEffect array to silence an ESLint warning creates stale closures; fix the effect logic or move values into refs/updaters instead of suppressing react-hooks/exhaustive-deps.
What is the exact timing difference between useEffect and useLayoutEffect relative to DOM mutations and browser painting?
Senior Engineering Answer
After React commits DOM mutations in the Commit phase, useLayoutEffect runs synchronously before the browser paints pixels to the screen, blocking visual paint until it finishes. Use it when you need to measure DOM layout (getBoundingClientRect, scrollHeight) and synchronously reposition a tooltip or scroll offset so the user never sees a one-frame flicker. useEffect is scheduled asynchronously after the browser has painted the frame, making it non-blocking and the right default for analytics, subscriptions, and data fetching.
useLayoutEffect(() => {
if (!tooltipRef.current || !anchorRef.current) return;
const rect = anchorRef.current.getBoundingClientRect();
tooltipRef.current.style.top = `${rect.bottom + 8}px`;
}, [isOpen]);Calling useLayoutEffect in Server-Side Rendered (SSR) components logs a warning because there is no DOM layout on the server; guard layout measurement behind client mount or useIsomorphicLayoutEffect only when necessary.
Why should you compute derived values during render instead of storing them in state and syncing with useEffect?
Senior Engineering Answer
Storing derived data (like filteredItems or fullName) in useState and updating it inside useEffect forces an unnecessary double render: React paints stale derived state first, runs the effect, calls setState, and re-renders a second time. Computing derived values directly during render (and wrapping genuinely expensive calculations in useMemo) eliminates the extra render pass, avoids out-of-sync bugs, and simplifies code. Similarly, to reset a component's internal state when an entity ID changes, pass key={entityId} instead of resetting multiple useState hooks inside an effect.
function FilteredList({ items, query }: { items: Item[]; query: string }) {
// Derived directly during render: single pass, always consistent
const visibleItems = useMemo(
() => items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())),
[items, query]
);
return <ul>{visibleItems.map((i) => <li key={i.id}>{i.name}</li>)}</ul>;
}Wrapping trivial expressions like 'items.length > 0' or 'first + last' in useMemo adds closure and dependency-comparison overhead that costs more than recomputing the expression.
When should you use useRef instead of useState, and how does useImperativeHandle expose controlled child APIs?
Senior Engineering Answer
useRef returns a mutable { current } container persisted across renders whose updates do NOT trigger re-renders. Use it for DOM element references, timer IDs, previous values, or WebSocket handles—anything that does not affect rendered output directly. When a parent needs imperative methods on a child (such as .focus() or .scrollToBottom()) without exposing the raw DOM node, pair ref forwarding (or React 19's direct ref prop) with useImperativeHandle to expose a minimal, encapsulated API.
interface ModalHandle {
focusConfirm: () => void;
}
function ConfirmDialog({ ref }: { ref?: React.Ref<ModalHandle> }) {
const btnRef = useRef<HTMLButtonElement>(null);
useImperativeHandle(ref, () => ({
focusConfirm: () => btnRef.current?.focus()
}), []);
return <button ref={btnRef}>Confirm</button>;
}Reading or writing ref.current during the render body violates React's pure-render rules and breaks concurrent rendering if renders are interrupted or replayed; only mutate refs inside event handlers or effects.
How does React Fiber work under the hood, and why does React separate the Render phase from the Commit phase?
Senior Engineering Answer
Before React 16, stack reconciliation walked the entire component tree recursively without yielding, blocking the main thread on large updates. React Fiber models each element as a linked-list node (with child, sibling, and return pointers) representing a unit of work. React maintains two trees—the Current tree (on screen) and the WorkInProgress tree (double buffering)—and splits updates into two phases: the Render (reconciliation) phase, which is pure, interruptible, and can pause/abort/restart across frames using priority lanes; and the Commit phase, which applies all collected DOM mutations, ref updates, and layout effects synchronously in one atomic pass so the user never sees a half-rendered UI.
// Conceptual Fiber links allow iterative traversal without call-stack recursion: // fiber.child -> first child Fiber // fiber.sibling -> next sibling Fiber // fiber.return -> parent Fiber // fiber.alternate -> counterpart in Current <-> WorkInProgress tree
Assuming component bodies execute strictly once per state change is wrong in Concurrent React: the Render phase can invoke a component multiple times before committing, which is why side effects during render are forbidden.
How do useTransition and useDeferredValue keep high-frequency UI interactions responsive during expensive re-renders?
Senior Engineering Answer
Urgent updates (typing in an input, clicking) run at high priority, whereas rendering a 5,000-row filtered table is expensive and non-urgent. Wrapping the secondary state update in startTransition (via useTransition) marks it as a low-priority transition lane: React renders the background tree interruptibly, yielding immediately if a new keystroke arrives and discarding stale in-progress renders. useDeferredValue achieves the same effect when you do not own the state setter (e.g., receiving a prop from a parent), returning the previous value while rendering the new value in the background.
function LiveFilter({ records }: { records: RecordItem[] }) {
const [input, setInput] = useState("");
const [filter, setFilter] = useState("");
const [isPending, startTransition] = useTransition();
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
const next = e.target.value;
setInput(next); // urgent: updates input immediately
startTransition(() => setFilter(next)); // interruptible background render
}
return (
<>
<input value={input} onChange={handleChange} />
{isPending && <span>Updating...</span>}
<HeavyResultsTable records={records} filter={filter} />
</>
);
}Do not wrap controlled text input state itself inside startTransition—the input cursor and characters will feel sluggish or drop characters because transitions are deferred.
When does React.memo fail to prevent child re-renders, and how does component composition (children prop) often solve it better?
Senior Engineering Answer
React.memo performs a shallow Object.is() comparison of props; it silently breaks if the parent passes a new inline object ({ style: { color: 'red' } }), an inline callback without useCallback, or inline JSX children (<MemoChild><span>hi</span></MemoChild>), because every parent render allocates fresh object/element references. Before adding useMemo/useCallback/React.memo everywhere, move fast-changing state down into a small leaf component or pass expensive subtrees via the children prop: React elements created by a grandparent retain referential identity when an intermediate wrapper re-renders.
function ScrollTracker({ children }: { children: React.ReactNode }) {
const [scrollY, setScrollY] = useState(0);
// HeavyChart passed as children was created by parent, so its React element
// reference stays identical when scrollY updates—no React.memo needed!
return (
<div onScroll={(e) => setScrollY(e.currentTarget.scrollTop)}>
<span>{scrollY}px</span>
{children}
</div>
);
}Remember that even a React.memo-wrapped component will still re-render whenever its own internal useState changes or a Context it consumes via useContext updates.
What is 'tearing' in Concurrent React, and how does useSyncExternalStore prevent it?
Senior Engineering Answer
Tearing happens when an external mutable store (like window.innerWidth, Redux, or a WebSocket store outside React state) mutates mid-render while React pauses between yielding slices of a concurrent render. Components rendered before the pause see version A of the store while components rendered after the pause see version B, producing an inconsistent UI. useSyncExternalStore takes (subscribe, getSnapshot, getServerSnapshot), forces React to detect snapshot changes via Object.is() before committing, and synchronously restarts/falls back to a consistent snapshot so all components agree on one store version.
function useOnlineStatus(): boolean {
return useSyncExternalStore(
(onStoreChange) => {
window.addEventListener("online", onStoreChange);
window.addEventListener("offline", onStoreChange);
return () => {
window.removeEventListener("online", onStoreChange);
window.removeEventListener("offline", onStoreChange);
};
},
() => navigator.onLine,
() => true // SSR snapshot
);
}Returning a newly constructed object or array from getSnapshot (e.g., () => ({ width: window.innerWidth })) causes an infinite render loop because Object.is() fails on every check; cache or return primitives.
How do React Server Components (RSC) differ from Server-Side Rendering (SSR), and how do you avoid poisoning the client bundle?
Senior Engineering Answer
SSR executes components on the server to produce initial HTML, then ships the full JavaScript bundle to hydrate the same components in the browser. React Server Components execute exclusively on the server, never ship their component code or server-only dependencies (DB clients, markdown parsers, secrets) to the browser, and stream serialized UI payloads (the RSC Payload) directly to React. Marking a module with 'use client' creates a client boundary: every module imported by a 'use client' file becomes part of the client bundle. Keep client boundaries as small leaf components and pass Server Components into them via props/children.
// ServerComponent.tsx (0 KB client JS)
import { db } from "@/lib/db";
import { ExpandablePanel } from "./ExpandablePanel"; // 'use client'
export async function AccountPage({ id }: { id: string }) {
const invoices = await db.invoices.findMany({ where: { accountId: id } });
return (
<ExpandablePanel title="Billing">
<ul>{invoices.map((inv) => <li key={inv.id}>{inv.total}</li>)}</ul>
</ExpandablePanel>
);
}Importing a Server Component directly inside a 'use client' file turns that component into a Client Component and breaks if it uses server-only APIs; pass it as children or a JSX prop from a Server parent instead.
How do Error Boundaries, Suspense boundaries, and React 19 form Actions/useOptimistic work together for resilient async UX?
Senior Engineering Answer
Error Boundaries (class components implementing getDerivedStateFromError and componentDidCatch) catch rendering and lifecycle errors in their subtree and render fallback UI without crashing the entire page—note they do NOT catch errors inside event handlers or detached setTimeout callbacks unless surfaced into state/transitions. Suspense boundaries catch thrown Promises (from lazy(), use(), or framework data loaders) to show localized skeletons and enable selective streaming hydration. React 19's useActionState manages async form action pending/error state cleanly, while useOptimistic displays immediate predicted state during a transition and automatically rolls back if the async action rejects.
function LikeButton({ likes, onLike }: { likes: number; onLike: () => Promise<void> }) {
const [optimisticLikes, addOptimistic] = useOptimistic(
likes,
(current: number, delta: number) => current + delta
);
const [, startTransition] = useTransition();
return (
<button onClick={() => startTransition(async () => {
addOptimistic(1);
await onLike();
})}>
Likes: {optimisticLikes}
</button>
);
}Calling addOptimistic outside a transition or async Action logs a React warning and immediately discards the optimistic state.
How do you systematically diagnose and eliminate severe UI lag and re-render storms in a large React application?
Senior Engineering Answer
Start by capturing a flamegraph in React DevTools Profiler ('Record why each component rendered') alongside Chrome Performance tab timings to distinguish React render CPU time from browser layout/paint thrashing. Common high-leverage fixes: (1) colocate ephemeral state (hover, modal open, input text) inside leaf components instead of top-level stores, (2) replace broad Context objects with atomic selectors (Zustand/Jotai/useSyncExternalStore) or split read/write Contexts, (3) virtualize large lists/tables (>100 rows) using @tanstack/react-virtual so only visible DOM rows mount, and (4) stabilize store selectors that return derived arrays/objects.
// Virtualized list renders only ~15 visible nodes instead of 10,000 DOM rows
const virtualizer = useVirtualizer({
count: rows.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 44,
overscan: 5
});Optimizing component render speed with React.memo while rendering 5,000 DOM nodes still causes 100ms+ browser style recalculation and layout pauses—virtualization solves DOM weight, not memoization.
What causes React hydration mismatches in SSR apps, and how do useId() and two-pass / external-store patterns resolve them cleanly?
Senior Engineering Answer
Hydration matches server-rendered HTML against the first client render pass. Mismatches occur when the server and client produce different markup or attributes—commonly from reading window/localStorage, formatting locale-dependent dates/timezones without an explicit timezone, using Math.random() for accessibility IDs, or invalid HTML nesting (like a <div> inside <p>). Use React's useId() for deterministic tree-position IDs across server and client, pass explicit timezone/locale from server headers, and for client-only values use useSyncExternalStore with a dedicated getServerSnapshot (or suppressHydrationWarning only on small leaf timestamps).
function FormField({ label }: { label: string }) {
const id = useId(); // identical on server and client across hydration
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} type="text" />
</div>
);
}Checking 'typeof window !== "undefined"' directly inside render to render different JSX on the client guarantees a hydration mismatch; defer client-only branches to useEffect or useSyncExternalStore's getServerSnapshot.
React.js Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis React.js preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Frontend & Core Web.
What is the difference between Controlled and Uncontrolled components in React forms, and when would you pick each?
How does React's reconciliation use the 'key' prop, and why is using the array index as key buggy for dynamic lists?
Why does calling setCount(count + 1) three times in one handler only increment by 1, and how does automatic batching work?
How does React Context work, and why can putting fast-changing state in a single Context hurt performance?
How do you prevent stale response race conditions when fetching data inside useEffect?
What is the exact timing difference between useEffect and useLayoutEffect relative to DOM mutations and browser painting?
Frequently Asked Technical Interview Questions (React.js)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
How does React's Virtual DOM reconciliation operate in O(n) time?
What is the difference between Server Components (RSC) and Client Components ('use client')?
Why is passing an array index as a React key an anti-pattern for stateful lists?
What is the difference between useEffect and useLayoutEffect?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.