
This is the list I wish I had before my first React loop: 300+ React interview questions, grouped by topic and ordered from basic to senior. Every question has an answer. Most link to a hands-on problem or a deeper write-up on FrontendLead, so you can practice instead of just reading.
React questions come up in almost every frontend interview, either as a dedicated round or mixed into a UI build. Interviewers rarely care whether you can recite a definition. They care whether you understand why React behaves the way it does, and whether you can debug it under pressure. The answers below are written with that in mind and follow the current React documentation.
What to Expect
- 14 sections, from fundamentals to React 19, Server Components, and senior-level architecture questions.
- Direct answers first, then the detail that turns a basic answer into a strong one: code, trade-offs, and common pitfalls.
- A dedicated section of React coding interview questions, each with the key idea and a link to solve it in the browser.
- Notes on what the interviewer is actually checking for the questions that trip people up.
If you’re short on time, read the sections marked for your level in How to Use This List at the end.
Jump to a section
- React Fundamentals (Q1-25)
- JSX and Components (Q26-50)
- Props, State, and Data Flow (Q51-75)
- Rendering, Reconciliation, and Keys (Q76-100)
- Core Hooks: useState, useRef, and useReducer (Q101-125)
- useEffect and Side Effects (Q126-150)
- Performance and Memoization (Q151-175)
- Context and State Management (Q176-200)
- Forms, Events, and Refs (Q201-220)
- Routing, Data Fetching, and Error Handling (Q221-240)
- React 18, React 19, and Server Components (Q241-260)
- Testing and Accessibility in React (Q261-275)
- React Coding Interview Questions (Q276-295)
- Senior React Interview Questions (Q296-310)
React Fundamentals

Find in-depth explanations and track your progress here: React JS Fundamentals ->
These are the warm-up questions. They sound easy, which is exactly why a vague answer hurts. Interviewers use them to see if you understand the model behind React, not just the API.
1. What is React, and what are its main features?
React is a JavaScript library for building user interfaces out of components. You describe what the UI should look like for a given state, and React updates the DOM to match when that state changes.
The features worth naming:
- Components: reusable functions that return UI.
- JSX: an HTML-like syntax that compiles to JavaScript function calls.
- Virtual DOM and reconciliation: React diffs the new UI description against the previous one and applies the minimum DOM changes.
- One-way data flow: data moves down through props; changes move up through callbacks.
- Hooks: state, effects, and other features in function components.
A strong answer adds the “why”: React makes UI a function of state, so you stop writing manual DOM update code that drifts out of sync.
2. Why use React instead of plain JavaScript and the DOM API?
With plain JavaScript you write two things: the initial render, and every transition between states (add this class, remove that node, update this text). The number of transitions grows fast, and each one is a chance for the DOM and your data to disagree.
React removes the transitions. You write one render function per component, and React computes the DOM changes. You also get composition (components inside components), a large ecosystem, and a consistent mental model across teams.
The honest trade-off: React adds bundle size and an abstraction layer. For a mostly static page, plain HTML and a little JavaScript can be the better choice.
3. Is React a library or a framework?
React itself is a library: it handles rendering and component state, and nothing else. It doesn’t ship a router, a data layer, or a build system.
In practice, most teams use React through a framework such as Next.js or React Router (framework mode), which adds routing, data loading, server rendering, and bundling. The React docs now recommend starting new apps with a framework for that reason.
4. What is the virtual DOM, and how does it work?
The virtual DOM is a lightweight JavaScript object tree that describes the UI. When state changes, React calls your components to produce a new tree, compares it with the previous one (reconciliation), and applies only the differences to the real DOM.
// JSX like <h1 className="title">Hi</h1> becomes an object similar to:
const element = {
type: 'h1',
props: { className: 'title', children: 'Hi' },
};
console.log(element.type); // "h1"
Practice: build one yourself in Virtual DOM I, then Virtual DOM II.
5. Is the virtual DOM faster than the real DOM?
Not by itself. Diffing is extra work on top of the DOM updates. A hand-written, perfectly targeted DOM update will always beat React.
The virtual DOM’s value is that it makes updates fast enough by default while you write declarative code. It batches changes and avoids touching DOM nodes that didn’t change, which is what naive “re-render everything with innerHTML” code gets wrong. Interviewers like hearing that you know the difference between “faster” and “good enough without manual work”.
6. What’s the difference between the virtual DOM and the shadow DOM?
| Aspect | Virtual DOM | Shadow DOM |
|---|---|---|
| What it is | A JavaScript copy of the UI tree | A browser feature for encapsulated DOM subtrees |
| Owned by | Libraries (React, Vue) | The browser (Web Components) |
| Purpose | Efficient updates | Style and markup isolation |
They solve unrelated problems and can be used together. More detail in React reconciliation.
7. What does “declarative” mean in React?
Declarative means you describe the result, not the steps. You say “when isOpen is true, render the menu”, and React figures out whether to insert, update, or remove nodes.
// Declarative: UI is derived from state
{isOpen && <Menu items={items} />}
// Imperative equivalent you no longer write:
// if (isOpen) container.appendChild(menuEl) else container.removeChild(menuEl)
8. What is one-way data flow?
Data flows from parent to child through props. A child can’t modify its props; to change data owned by a parent, the child calls a function the parent passed down.
This makes bugs easier to trace: if some data is wrong, you look at whoever owns that state, not at every component that reads it. Compare it with two-way binding (Angular’s [(ngModel)]), where a change can come from either side.
9. What is a component?
A component is a function that takes props and returns UI (JSX). Components let you split the interface into independent, reusable pieces, each owning its own markup, logic, and state.
function Avatar({ src, name }) {
return <img className="avatar" src={src} alt={name} />;
}
Component names must start with a capital letter. JSX treats lowercase tags as built-in HTML elements.
10. Function components vs class components: which should you use?
Use function components with hooks for all new code. Class components still work, but the React team designs new features (hooks, the React Compiler, Server Components) around functions.
| Aspect | Function component | Class component |
|---|---|---|
| State | useState, useReducer | this.state, this.setState |
| Side effects | useEffect | componentDidMount / DidUpdate / WillUnmount |
| Logic reuse | Custom hooks | HOCs, render props |
| Still required for | – | Error boundaries |
That last row is a good detail to mention: error boundaries still require a class (or a library such as react-error-boundary that wraps one).
11. What are the lifecycle phases of a React component?
Three phases: mounting (first time it appears), updating (re-rendering because state, props, or context changed), and unmounting (removed from the tree).
In function components you don’t hook into phases directly. You synchronize with effects: an effect runs after mount, re-runs after updates when its dependencies change, and its cleanup runs before the next run and on unmount. See Lifecycle Methods.
12. How do class lifecycle methods map to hooks?
| Class method | Hook equivalent |
|---|---|
| constructor | useState initializer |
| componentDidMount | useEffect(fn, []) |
| componentDidUpdate | useEffect(fn, [deps]) |
| componentWillUnmount | Cleanup returned from useEffect |
| shouldComponentUpdate | React.memo |
| getSnapshotBeforeUpdate | No direct equivalent (useLayoutEffect is closest) |
The mapping is a starting point, not a rule. Thinking “which external system am I syncing with?” produces better effects than thinking “what lifecycle method is this?”.
13. What is React Fiber?
Fiber is React’s reconciliation engine, introduced in React 16. It represents each component as a unit of work (a “fiber”) in a linked tree, so React can pause rendering, give the browser a chance to handle input, and resume later.
Fiber is what makes concurrent features possible: startTransition, Suspense, and prioritizing urgent updates (typing) over non-urgent ones (filtering a big list).
14. What’s the difference between react and react-dom?
react contains the core: components, hooks, and the element model. react-dom is the renderer that turns React trees into browser DOM nodes (createRoot, hydrateRoot, createPortal).
The split exists because React renders to more than the DOM: React Native renders to native views, and other renderers target canvas, PDFs, or the terminal.
15. How do you start a new React project in 2026?
Create React App was deprecated in early 2025, so don’t suggest it. The current options:
- A framework (Next.js, React Router framework mode) for apps that need routing, data loading, and server rendering.
- Vite with the React template for a client-only app or a quick prototype.
Mentioning why CRA was retired (slow builds, no routing or data-fetching story) shows you follow the ecosystem.
16. What does createRoot do?
createRoot creates a React root attached to a DOM node, and root.render() renders your app into it. It’s the React 18+ API and enables concurrent features.
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
For server-rendered HTML, you use hydrateRoot instead, which attaches React to the existing markup rather than replacing it.
17. What is StrictMode, and why does my effect run twice?
<StrictMode> is a development-only wrapper that surfaces bugs early. It renders components twice to catch impure render logic, and it mounts, unmounts, and re-mounts components to check that effects clean up properly.
So an effect that runs twice in development is StrictMode doing its job. If the double run causes a bug (two subscriptions, two analytics events), the effect is missing a cleanup. Nothing runs twice in production.
18. Element vs component vs instance: what’s the difference?
- Component: the function (or class) you write, like
Button. - Element: the plain object JSX creates, like
<Button label="Save" />. It describes what to render. - Instance: for class components, the object React creates with
this. Function components have no instances; React stores their state on the fiber.
19. Why must React components be pure?
A pure component returns the same JSX for the same props, state, and context, and doesn’t change anything outside itself during render. React relies on this to render components in any order, render them more than once, or skip them.
let count = 0;
function Impure() {
count++; // ❌ mutates outside state during render
return <p>Rendered {count} times</p>;
}
Side effects belong in event handlers or effects, never in the render body. This rule is also what lets the React Compiler memoize your code automatically.
20. What counts as a side effect in React?
Anything that reaches outside the component’s render: network requests, subscriptions, timers, reading or writing localStorage, manually changing the DOM, logging analytics, or mutating variables outside the component.
Put side effects that respond to a user action in the event handler. Put side effects that keep the component in sync with an external system in useEffect.
21. What libraries usually surround React in a real app?
| Need | Common choices |
|---|---|
| Framework / routing | Next.js, React Router, TanStack Router |
| Server data | TanStack Query, SWR, Apollo / Relay for GraphQL |
| Client state | Context, Zustand, Redux Toolkit, Jotai |
| Forms | React Hook Form, plus Zod for validation |
| Testing | Vitest or Jest, React Testing Library, Playwright |
Interviewers don’t need you to know them all. They want to hear that you pick tools for a reason, such as “server data goes in a cache, not in Redux”.
22. How does React compare with Angular and Vue?
| Aspect | React | Angular | Vue |
|---|---|---|---|
| Type | UI library | Full framework | Progressive framework |
| Templates | JSX | HTML templates | HTML templates (or JSX) |
| Reactivity | Re-render on state change | Signals, zone.js change detection | Proxy-based reactivity |
| Opinionated | Low | High | Medium |
Avoid trashing the other frameworks. “React gives flexibility at the cost of more decisions” is a better answer than “React is the best”.
23. What is a single-page application, and what are its downsides?
An SPA loads one HTML page and then updates the view with JavaScript as the user navigates, without full page reloads. Navigation feels instant after the first load.
The downsides: a larger initial JavaScript download, a blank or loading screen until it runs, weaker SEO if content is only rendered on the client, and more work for accessibility (focus and announcements on route changes). Server rendering and code splitting address most of these.
24. CSR vs SSR vs SSG: what’s the difference?
| Strategy | HTML is built | Good for |
|---|---|---|
| CSR (client-side rendering) | In the browser | Dashboards behind login |
| SSR (server-side rendering) | On the server, per request | Personalized pages that need SEO |
| SSG (static generation) | At build time | Docs, blogs, marketing pages |
Frameworks let you mix them per route, and incremental static regeneration adds “static, but refreshed every N seconds”. Deep dive: SSR vs CSR.
25. What is hydration?
Hydration is React attaching event handlers and state to HTML that was already rendered on the server. The user sees content immediately, and the page becomes interactive once the JavaScript loads and hydrates it.
If the server HTML and the first client render don’t match (for example, rendering Date.now() or reading window during render), React reports a hydration mismatch. The fix is to render the same output on both sides and move browser-only values into an effect.
JSX and Components

Find in-depth explanations and practice here: React coding questions ->
JSX questions test whether you know what your code compiles to. Component pattern questions test whether you can structure a codebase other people can work in.
26. What is JSX?
JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. A compiler (Babel, SWC, esbuild) turns it into function calls that create React elements.
// You write:
const el = <button onClick={save}>Save</button>;
// The modern JSX transform compiles it to roughly:
import { jsx as _jsx } from 'react/jsx-runtime';
const el = _jsx('button', { onClick: save, children: 'Save' });
Since the “new JSX transform” (React 17), you no longer need import React at the top of every file.
27. Can you use React without JSX?
Yes. JSX is optional sugar over React.createElement(type, props, ...children). Almost nobody skips it, because nested createElement calls are hard to read, but knowing the equivalence shows you understand there’s no magic in JSX.
28. Why does JSX use className and htmlFor?
JSX maps to JavaScript object properties, and class and for are reserved words in JavaScript. React uses the DOM property names instead: className and htmlFor. The same reason explains camelCase attributes like onClick and tabIndex.
29. How do you embed JavaScript expressions in JSX?
Wrap any expression in curly braces: variables, function calls, ternaries, template literals. Statements (if, for) aren’t allowed inside JSX, because JSX attributes and children must be expressions.
<p className={`status ${isActive ? 'on' : 'off'}`}>
{user.firstName} has {items.length} items
</p>
30. What are the ways to render something conditionally?
- Early return for whole-component branches:
if (!user) return <Login />; - Ternary to choose between two elements.
- && to render something or nothing.
The classic bug: {items.length && <List />} renders a literal 0 when the list is empty, because 0 is a valid React child. Use {items.length > 0 && <List />}. Interviewers love this one.
31. How do you render a list in React?
Map the array to elements and give each one a stable, unique key, usually the item’s id.
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
Keys are covered in depth in the rendering section.
32. What are fragments, and when do you need them?
A fragment groups children without adding a DOM node. Use <>...</>, or <Fragment key={id}> when the group needs a key inside a list.
They matter for valid markup: a component that returns several <td> cells or <li> items can’t wrap them in a <div> without breaking the table or list.
33. Why must a component return a single root element?
A component returns one value, and JSX compiles each tag to one function call. Two sibling tags would be two values, which a function can’t return without wrapping them. A fragment or an array solves it.
34. What is props.children?
children is the prop that holds whatever you put between a component’s opening and closing tags. It lets you build wrapper components (cards, layouts, modals) without knowing their content.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
<Card title="Profile"><Avatar /><Bio /></Card>
35. Why does React favor composition over inheritance?
Components share behavior by containing each other and passing props or children, not by extending base classes. Composition keeps each component independent: a Dialog can wrap any content without a ConfirmDialog extends Dialog hierarchy that breaks when requirements change.
For shared logic (not UI), use custom hooks.
36. What are the common ways to style React components?
| Approach | Strength | Watch out for |
|---|---|---|
| CSS Modules | Scoped class names, plain CSS | Dynamic styles need class toggling |
| Tailwind CSS | Fast, consistent design tokens | Long class strings |
| Runtime CSS-in-JS (styled-components) | Styles from props | Runtime cost, awkward with Server Components |
| Zero-runtime CSS-in-JS (vanilla-extract, Panda) | Type-safe, compiled to CSS | Build setup |
A senior detail: runtime CSS-in-JS libraries need client-side JavaScript to inject styles, which is why many teams moved to compiled approaches with Server Components.
37. How do inline styles work in JSX?
The style prop takes an object with camelCase property names, not a string. Numeric values get px added for most properties.
<div style={{ marginTop: 8, backgroundColor: 'tomato' }} />
Inline styles can’t express pseudo-classes (:hover) or media queries, so use them for truly dynamic values (a computed width) and classes for everything else.
38. What is dangerouslySetInnerHTML?
It’s React’s replacement for setting innerHTML. The awkward name is a warning: inserting raw HTML bypasses React’s escaping and can open an XSS hole.
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />
Only use it with trusted or sanitized HTML, such as CMS content passed through a sanitizer.
39. How does React protect against XSS by default?
React escapes every string you render as text, so <p>{userInput}</p> displays <script> as characters instead of running it.
The gaps you still own: dangerouslySetInnerHTML, href values like javascript:alert(1) from user input, and server-rendered data injected into a <script> tag. See XSS vs CORS.
40. What is a higher-order component (HOC)?
An HOC is a function that takes a component and returns a new component with extra behavior, like withAuth(Dashboard).
function withLoading(Component) {
return function WithLoading({ isLoading, ...props }) {
return isLoading ? <Spinner /> : <Component {...props} />;
};
}
HOCs are mostly legacy now. Their problems: wrapper nesting in DevTools, prop name collisions, and hidden data sources. Custom hooks solve the same reuse problem more directly. See Higher-order components.
41. What are render props?
A render prop is a function prop that a component calls to decide what to render, passing it some internal state.
<MouseTracker render={({ x, y }) => <Cursor x={x} y={y} />} />
Like HOCs, render props have mostly been replaced by hooks (const { x, y } = useMouse()), but you’ll still see them in libraries such as headless UI components and virtualized lists.
42. What is a custom hook?
A custom hook is a function whose name starts with use and that calls other hooks. It extracts stateful logic so several components can reuse it. Each component that calls the hook gets its own independent state.
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const update = () => setIsOnline(navigator.onLine);
window.addEventListener('online', update);
window.addEventListener('offline', update);
return () => {
window.removeEventListener('online', update);
window.removeEventListener('offline', update);
};
}, []);
return isOnline;
}
Practice writing hooks: useDebouncedValue, useMatchMedia, useDomEvent.
43. What are presentational and container components?
A pattern where presentational components only render props, and container components fetch data and manage state. It made components easy to reuse and test.
Hooks blurred the line, since data logic now lives in hooks rather than wrapper components. The underlying idea still holds: keep rendering separate from data logic. On FrontendLead we call this MVVM; see MVVM Design Pattern in React.
44. What is the compound components pattern?
A set of components that work together and share implicit state through context, giving the user a flexible, declarative API. Think of <select> and <option>.
<Tabs defaultValue="profile">
<Tabs.List>
<Tabs.Trigger value="profile">Profile</Tabs.Trigger>
<Tabs.Trigger value="billing">Billing</Tabs.Trigger>
</Tabs.List>
<Tabs.Panel value="profile">...</Tabs.Panel>
</Tabs>
It avoids “prop soup” like <Tabs tabs={[...]} renderPanel={...} />. Build one in Tabs or Accessible Tabs.
45. What are portals, and when do you use them?
createPortal(children, domNode) renders children into a different DOM node, usually document.body, while keeping them in the same place in the React tree.
Use them for modals, tooltips, and toasts that must escape a parent’s overflow: hidden or stacking context. Two details interviewers like: events still bubble through the React tree (not the DOM tree), and context still works inside the portal.
46. How do you code-split React components?
Wrap a dynamic import in React.lazy and render it inside Suspense with a fallback. The component’s code downloads only when it’s first rendered.
const Settings = lazy(() => import('./Settings'));
<Suspense fallback={<Spinner />}>
<Settings />
</Suspense>
Good split points are routes and heavy, rarely used UI (editors, charts, modals). More in Code Splitting and Lazy Loading.
47. How do you set default props in a function component?
Use default values in destructuring: function Button({ size = 'md', variant = 'primary' }).
Component.defaultProps was removed for function components in React 19 (it still works for classes). If you see it in an old codebase, it’s a migration item.
48. How do you type props with TypeScript?
Declare an interface or type for the props and annotate the destructured parameter. Use React.ReactNode for anything renderable and the built-in element types to extend native props.
interface ButtonProps extends React.ComponentPropsWithoutRef<'button'> {
variant?: 'primary' | 'ghost';
children: React.ReactNode;
}
function Button({ variant = 'primary', children, ...rest }: ButtonProps) {
return <button className={variant} {...rest}>{children}</button>;
}
49. What do null, false, undefined, and 0 render in JSX?
null, undefined, true, and false render nothing. Numbers (including 0 and NaN) and strings render as text. That asymmetry is the root cause of the && bug in question 30.
50. Why shouldn’t you define a component inside another component?
Every render of the parent creates a new function, so React sees a different component type each time. It unmounts the old one and mounts a new one, which resets its state, loses input focus, and re-runs its effects.
function Parent() {
// ❌ New component type every render: the input loses focus on each keystroke
function Field() { return <input />; }
return <Field />;
}
Define components at the top level and pass data through props.
Props, State, and Data Flow

Find in-depth explanations and practice here: Props and State ->
Most React bugs come from state in the wrong place, stale state, or state that duplicates other state. This section is where interviewers separate “has used React” from “understands React”.
51. What’s the difference between props and state?
| Aspect | Props | State |
|---|---|---|
| Owned by | The parent | The component itself |
| Mutable by the component | No | Yes, through the setter |
| Changing it | Parent re-renders with new values | Setter schedules a re-render |
| Analogy | Function arguments | A component’s memory |
One component’s state often becomes another component’s props. That’s how data flows down the tree.
52. Why are props read-only?
If a child could change its props, the parent’s data would change behind its back, and you’d lose one-way data flow. React also relies on props being stable inputs for purity: the same props must produce the same output. To change a prop’s value, the child asks the parent through a callback.
53. What does “lifting state up” mean?
When two components need the same changing data, you move the state to their closest common parent and pass it down as props, along with a setter or callback.
function Converter() {
const [celsius, setCelsius] = useState(0);
return (
<>
<CelsiusInput value={celsius} onChange={setCelsius} />
<FahrenheitInput value={celsius * 9 / 5 + 32} onChange={(f) => setCelsius((f - 32) * 5 / 9)} />
</>
);
}
Practice exactly this: Linked Temperature Fields.
54. What is prop drilling, and how do you avoid it?
Prop drilling is passing a prop through several components that don’t use it, just so a deeply nested child can. A few levels is fine and explicit. Many levels make refactoring painful.
Fixes, in the order I’d reach for them:
- Composition: pass the finished child element down as
children, so the middle layers never see the data. - Context for values many components read (theme, current user).
- A store (Zustand, Redux Toolkit) for complex shared client state.
55. Is setState synchronous or asynchronous?
Neither, exactly. Calling a setter doesn’t change the variable you’re holding; it schedules a re-render with the new value. The current render keeps seeing the old value.
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // still 0: this render's snapshot
}
56. What is automatic batching?
React groups multiple state updates into one re-render. Since React 18 this happens everywhere: event handlers, promises, setTimeout, and native event listeners. Before 18, only updates inside React event handlers were batched.
If you truly need the DOM updated immediately (rare, such as scrolling to a newly added item), flushSync from react-dom forces a synchronous update.
57. Why shouldn’t you mutate state directly?
React decides whether to re-render by comparing the old and new state with Object.is. If you mutate the existing object and pass it back, the reference is the same, so React may skip the update. Mutations also break memoization, time-travel debugging, and concurrent rendering, which can read state from an earlier render.
// ❌ Same reference: React may not re-render
user.name = 'Ada';
setUser(user);
// ✅ New object
setUser({ ...user, name: 'Ada' });
Background: Mutable vs Immutable.
58. How do you update a nested object in state?
Copy every level you change, from the top down to the changed field. The spread operator is shallow, so nested objects must be spread too.
setForm((prev) => ({
...prev,
address: { ...prev.address, city: 'Austin' },
}));
If this gets deep, either flatten the state shape or use Immer (built into Redux Toolkit), which lets you write mutating syntax on a draft and produces an immutable copy.
59. How do you add, remove, and update items in an array in state?
const todos = [{ id: 1, done: false }, { id: 2, done: false }];
const added = [...todos, { id: 3, done: false }]; // add
const removed = todos.filter((t) => t.id !== 1); // remove
const toggled = todos.map((t) => (t.id === 2 ? { ...t, done: true } : t)); // update
console.log(added.length, removed.length, toggled[1].done); // 3 1 true
Avoid push, splice, sort, and reverse on state arrays, since they mutate. Use toSorted() and toReversed(), or copy first.
60. What is derived state, and why shouldn’t you store it?
Derived state is any value you can compute from existing props or state, such as a filtered list or a full name. Storing it in its own useState means keeping two sources in sync, usually with an effect, and they eventually drift.
// ❌ Extra state + effect to keep it in sync
const [visible, setVisible] = useState([]);
useEffect(() => setVisible(todos.filter((t) => !t.done)), [todos]);
// ✅ Compute during render
const visible = todos.filter((t) => !t.done);
If the calculation is expensive, wrap it in useMemo. Don’t add state.
61. Should you copy props into state?
Usually not. useState(props.value) only uses the prop on the first render, so later prop changes are ignored, and the component shows stale data.
It’s fine when the prop is explicitly an initial value, and the name should say so: initialValue or defaultValue. If you need to reset internal state when a prop changes, change the component’s key instead.
62. What does “single source of truth” mean in React?
Each piece of data is owned by exactly one component (or store), and everyone else reads it through props or context. If two components each hold their own copy of “selected item”, they will disagree at some point. Pick an owner, lift state there, and derive everything else.
63. How does a child send data to its parent?
The parent passes a callback prop; the child calls it with the data.
function SearchBox({ onSearch }) {
const [query, setQuery] = useState('');
return (
<form onSubmit={(e) => { e.preventDefault(); onSearch(query); }}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
</form>
);
}
64. How do sibling components communicate?
Through their common parent: lift the shared state to the parent, pass the value to one sibling, and the setter to the other. If the siblings are far apart in the tree, use context or a store. There is no direct sibling-to-sibling channel in React, and that’s on purpose.
65. What is state colocation?
Keep state as close as possible to where it’s used. If only a dropdown needs isOpen, it belongs in the dropdown, not in a global store or a page component.
Colocation reduces re-renders (only the subtree that owns the state re-renders) and makes components easier to delete or move. Lift state only when a second component actually needs it. More in Local, Lifted, and Global State.
66. When does React reset a component’s state?
React ties state to a component’s position in the tree and its type. State is preserved as long as the same component type renders at the same position (with the same key). It resets when:
- The component unmounts (conditionally removed).
- A different component type renders at that position.
- Its
keychanges.
A common surprise: {isAdmin ? <Form /> : <Form />} keeps the same state in both branches, because it’s the same type at the same position.
67. How do you reset a component’s state on purpose?
Give it a key that changes when it should reset. React treats a new key as a new component and mounts it fresh.
// Switching users clears the draft message
<ChatInput key={contactId} contactId={contactId} />
This replaces a lot of “reset state when prop changes” effects, which cause an extra render with stale values.
68. What does “state as a snapshot” mean?
Each render gets its own fixed values of props and state. Event handlers and effects created during that render “see” those values forever, even if state changes later.
function handleSend() {
setTimeout(() => alert(`Sending: ${message}`), 3000);
}
// If the user edits the message during those 3 seconds,
// the alert still shows the message from the render where they clicked.
This explains most “stale state” bugs. The cause is closures; see Closures.
69. When should you use the updater function form of setState?
Use setCount(c => c + 1) whenever the new state depends on the previous state, especially with several updates in a row, or inside timers and subscriptions created in an earlier render.
// Adds 1, not 3: every call sees the same snapshot
setCount(count + 1); setCount(count + 1); setCount(count + 1);
// Adds 3: each updater receives the latest pending value
setCount((c) => c + 1); setCount((c) => c + 1); setCount((c) => c + 1);
70. How do you build a component that can be both controlled and uncontrolled?
Follow the native input convention: accept value plus onChange for controlled use, and defaultValue for uncontrolled use. Internally, use the prop when it’s defined, otherwise your own state.
function Toggle({ checked, defaultChecked = false, onChange }) {
const [internal, setInternal] = useState(defaultChecked);
const isControlled = checked !== undefined;
const value = isControlled ? checked : internal;
function toggle() {
if (!isControlled) setInternal(!value);
onChange?.(!value);
}
return <button role="switch" aria-checked={value} onClick={toggle} />;
}
Practice a related hook: useSwitch.
71. What tools help with immutable updates?
- Spread syntax and array methods that return copies (
map,filter,toSorted,with). structuredClonefor a full deep copy (fine for small data, wasteful for big trees).- Immer for deeply nested updates with readable code.
Deep-cloning everything on every update is a red flag in interviews. Copy only the path that changed, so unchanged subtrees keep their references and memoized children can skip re-rendering.
72. What are the risks of spreading props ({…props})?
Spreading forwards every prop, including ones the child doesn’t expect. Unknown props can land on DOM elements (React warns about invalid attributes), override props you set earlier, and make it hard to see what a component accepts.
It’s fine for wrapper components that intentionally forward native attributes. Destructure the props you use first, then spread the rest: function Input({ label, ...inputProps }).
73. How do you validate props in 2026?
With TypeScript at compile time. React 19 removed propTypes checks entirely, so Component.propTypes is silently ignored now.
For data coming from outside your code (API responses, URL params, form input), add runtime validation with a schema library such as Zod. Types don’t exist at runtime.
74. Why is storing a function in state tricky?
Both useState and the setter treat a function argument specially. useState(fn) calls fn as a lazy initializer, and setState(fn) calls it as an updater. To store the function itself, wrap it:
const [onConfirm, setOnConfirm] = useState(() => defaultHandler);
setOnConfirm(() => newHandler);
Often a ref is the better place for a callback that doesn’t affect rendering.
75. How should you structure component state?
The rules I follow, and the ones interviewers look for:
- Group related state that always changes together (x and y into one position object).
- Avoid contradictions: replace
isLoading,isError,isSuccessbooleans with onestatusvalue, so “loading and error at the same time” can’t happen. - Avoid redundancy: don’t store what you can derive.
- Avoid duplication: store
selectedId, not a copy of the selected object. - Avoid deep nesting: normalize by id when items reference each other.
// ❌ Four booleans allow 16 combinations, most of them invalid
// ✅ One value, only valid states
const [status, setStatus] = useState('idle'); // 'idle' | 'loading' | 'success' | 'error'
Rendering, Reconciliation, and Keys

Find in-depth explanations and practice here: React Rendering and Re-renders ->
Almost every React question maps to one of four steps: what triggers a render, what happens during render, what gets committed to the DOM, and when effects run. If you can place a question on that pipeline, you can usually reason your way to the answer.
76. What causes a component to re-render?
Three things:
- Its own state changes.
- Its parent re-renders. By default, children re-render with the parent even if their props didn’t change.
- A context it reads changes.
The common mistake is answering “when its props change”. Props changing isn’t a trigger by itself; the parent re-rendering is. That’s why React.memo exists: it lets a child skip re-rendering when its props are shallowly equal.
77. If a parent re-renders with the same props, does the child re-render?
Yes, unless the child is wrapped in React.memo (or compiled by the React Compiler, which memoizes automatically). React doesn’t compare props by default, because comparing costs time too, and most renders are cheap.
78. What are the render phase and the commit phase?
| Phase | What happens | Can be interrupted? |
|---|---|---|
| Render | React calls components and diffs the result | Yes (concurrent rendering) |
| Commit | React applies DOM changes, updates refs, runs layout effects | No, it’s synchronous |
| Passive effects | useEffect callbacks run, usually after paint | – |
Because render can run more than once or be thrown away, it must be pure. Side effects belong in the commit or effect phases.
79. Walk me through what happens after you call setState.
- Trigger: React queues the update and schedules a render, batching other updates from the same event.
- Render: React calls the component (and its children) to get new JSX, then reconciles it against the previous tree.
- Commit: React applies the minimal DOM changes, attaches refs, and runs
useLayoutEffect. - Paint: the browser paints the screen.
- Effects: React runs cleanup for changed effects, then the new
useEffectcallbacks.
Being able to recite this pipeline is the single most useful thing for debugging questions.
80. What is reconciliation, and what heuristics does the diff use?
Reconciliation is how React compares the new element tree with the old one to decide what to change. A perfect tree diff is O(n³), so React uses two heuristics to make it O(n):
- Different type, different tree. If a
<div>becomes a<section>, or<A />becomes<B />, React tears down the old subtree (losing its state) and builds a new one. - Keys identify children. In lists, React matches old and new children by key instead of by position.
Deep dive: React reconciliation.
81. Why does React need keys?
Keys tell React which items in a list are the same item between renders. Without stable keys, React matches items by position.
The strong answer includes a concrete bug. If you use the array index as a key and insert an item at the top, every item’s index shifts. React thinks item 0 is still item 0, so internal state (the text in an uncontrolled input, an “expanded” toggle) stays attached to the wrong row.
// ❌ State gets attached to the wrong row when the list is reordered
{todos.map((todo, i) => <TodoRow key={i} todo={todo} />)}
// ✅ Stable identity
{todos.map((todo) => <TodoRow key={todo.id} todo={todo} />)}
82. When is it okay to use the index as a key?
When all three hold: the list is never reordered or filtered, items are never inserted or removed except at the end, and the items have no state or uncontrolled inputs. A static list of labels is fine. A to-do list is not.
If items have no id, generate one when you create the item (crypto.randomUUID()), not during render.
83. What happens if two siblings have the same key?
React warns in development, and behavior becomes unpredictable: it may drop one of the items, duplicate one, or attach state to the wrong one. Keys must be unique among siblings, not globally. The same id can appear in two different lists.
84. Can you use Math.random() as a key?
No. A new key on every render tells React every item is new, so it unmounts and remounts the entire list each time. You lose input focus and state, and performance tanks. Keys must be stable across renders.
85. Can a component read its own key?
No. key (like ref in older versions) is consumed by React and not passed in props. If the child needs the id, pass it again under another name: <Row key={item.id} id={item.id} />.
86. Does a re-render always update the DOM?
No. A re-render means React called your component again. If the resulting JSX is the same as last time, the commit phase changes nothing in the DOM. That’s why “too many re-renders” is usually a CPU problem, not a DOM problem, and often not a problem at all.
87. What happens if you set state to the same value?
React compares the new value with the current one using Object.is. If they’re equal, it bails out and skips re-rendering the children. (React may still call the component itself once before bailing out, which is harmless.)
This is also why mutating an object and setting it again doesn’t work: it’s the same reference, so Object.is says nothing changed.
88. How do you find out why a component re-rendered?
- React DevTools Profiler: record an interaction, then check “Why did this render?” for each component (enable it in the profiler settings).
- “Highlight updates when components render” in DevTools settings, to see re-renders visually.
- A temporary
console.login the render body, which is crude but fast.
Measure before optimizing. Most re-renders are cheap, and the real cost is usually a single slow component.
89. Does a context change re-render every consumer?
Yes. Every component that calls useContext(SomeContext) re-renders when the provider’s value changes, even if it only uses one field from it. React.memo doesn’t block context updates.
That’s why context is great for values that rarely change (theme, locale, current user) and poor for fast-changing values. Mitigations are in Avoiding Context Re-render Pitfalls.
90. What’s the difference between rendering and painting?
“Rendering” in React means calling components to compute the UI. “Painting” is the browser drawing pixels after layout. React’s commit updates the DOM; the browser then recalculates styles and layout, and paints. A React render can produce zero paint work if nothing changed. See Reflow vs repaint.
91. What is tearing, and how does React prevent it?
Tearing is when different parts of the UI show different versions of the same data during one render. It can happen with concurrent rendering if a component reads from an external mutable store (a global variable, a non-React store) that changes while React is mid-render.
useSyncExternalStore prevents it by forcing a synchronous re-render when the store changes. State libraries such as Redux and Zustand use it under the hood.
92. What’s the difference between re-rendering and re-mounting?
Re-rendering calls the component again and keeps its state, refs, and DOM nodes. Re-mounting destroys the component (running effect cleanups, discarding state and DOM) and creates a fresh one. Re-mounting happens when the key changes, the component type at that position changes, or it’s removed and added back.
93. Why doesn’t content passed as children re-render when the wrapper’s state changes?
Because the children elements were created by the parent of the wrapper. When the wrapper’s state changes, React re-renders the wrapper, but props.children is the same element object as before, so React skips it.
function ScrollTracker({ children }) {
const [y, setY] = useState(0);
// ...updates y on scroll
return <div>{children}</div>; // children don't re-render on scroll
}
<ScrollTracker><ExpensiveTree /></ScrollTracker>
This “lift content up” trick fixes many performance problems without any memoization.
94. What is shallow comparison?
Shallow comparison checks each top-level property with Object.is. Primitives compare by value; objects, arrays, and functions compare by reference.
const a = { id: 1, tags: ['x'] };
const b = { id: 1, tags: ['x'] };
console.log(Object.is(a.id, b.id)); // true
console.log(Object.is(a.tags, b.tags)); // false: different arrays
React.memo and hook dependency arrays both use it, which is why a new inline object or function breaks memoization.
95. How does React handle events?
React wraps native events in SyntheticEvent objects with a consistent API across browsers. Instead of attaching a listener to every element, React attaches one listener per event type at the root and dispatches events to your handlers (event delegation).
Two details: the native event is available as e.nativeEvent, and returning false from a handler does not prevent the default action; call e.preventDefault(). Background: Event Delegation.
96. What changed about event delegation in React 17?
React used to attach its listeners to document. Since React 17, it attaches them to the root container you render into. That makes it safe to run several React versions on one page (micro frontends) and fixes surprises where e.stopPropagation() in React didn’t stop native listeners on document.
97. Does React re-render the whole app on every state change?
No. It re-renders the component whose state changed and its descendants, unless a descendant bails out through React.memo or the children-as-props pattern. Components above and beside it are untouched. This is the main argument for colocating state low in the tree.
98. Can you call setState during render?
Only in one narrow case: updating the same component’s state in response to a prop change, guarded by a condition. React then re-runs the component immediately before committing.
function List({ items }) {
const [prevItems, setPrevItems] = useState(items);
const [selection, setSelection] = useState(null);
if (items !== prevItems) {
setPrevItems(items);
setSelection(null); // reset when items change
}
// ...
}
It’s better than an effect (no extra render with stale values), but a key reset or derived value is usually simpler. Setting another component’s state during render is an error.
99. What causes the “Too many re-renders” error?
An unconditional state update during render, which triggers another render, which updates state again. The usual culprit is calling a handler instead of passing it:
// ❌ Calls setOpen during render, every render
<button onClick={setOpen(true)}>Open</button>
// ✅ Passes a function to call on click
<button onClick={() => setOpen(true)}>Open</button>
The effect version of this bug (an effect that sets state it depends on, with no condition) causes an infinite loop rather than this error.
100. When should you actually care about re-renders?
When a user can feel it: typing lag, janky scrolling, slow interactions (a poor INP score). Re-renders are a problem when a component is expensive (big lists, heavy calculations, charts) and renders often (every keystroke, every scroll event).
The senior answer: profile, find the one expensive subtree, then fix it with colocation, children-as-props, memoization, virtualization, or a transition. See Debugging INP in React apps.
Core Hooks: useState, useRef, and useReducer

Find in-depth explanations and practice here: React Hooks ->
Hooks questions range from “what does useRef do” to “implement useInterval without stale closures”. The second kind is where offers are won, so the coding examples here matter more than the definitions.
101. What are hooks, and why were they introduced?
Hooks are functions that let function components use React features: state, effects, context, refs. They shipped in React 16.8 to fix three problems with classes:
- Reusing stateful logic required HOCs or render props, which nested deeply.
- Related logic was split across lifecycle methods (subscribe in
componentDidMount, unsubscribe incomponentWillUnmount). - Classes were harder to optimize and confusing with
thisbinding.
102. What are the rules of hooks?
- Only call hooks at the top level: not inside conditions, loops, nested functions, or after an early return.
- Only call hooks from React function components or custom hooks, not from regular functions or classes.
The eslint-plugin-react-hooks package enforces both, plus the dependency rules for effects. Every React project should have it on.
103. Why can’t hooks be called conditionally?
React doesn’t identify hooks by name. It stores each component’s hook state in a list and matches calls by their order. If a hook is skipped on one render, every hook after it reads the wrong slot.
function Profile({ user }) {
if (!user) return null; // ❌ early return before a hook
const [tab, setTab] = useState('posts');
// On a render where user is null, React sees 0 hooks; next render, 1 hook.
}
Move the condition inside the hook’s logic, or move the hook above the early return.
104. How does useState work under the hood?
Each component’s fiber holds a linked list of hook objects. On the first render, useState creates an entry with the initial value and an update queue. On later renders, React walks the same list in order, applies queued updates, and returns the current value plus a setter bound to that entry.
That’s why the order rule exists, and why the setter is stable: it always points at the same hook entry.
105. What is lazy initial state?
Passing a function to useState makes React call it only on the first render. Use it when the initial value is expensive to compute.
// ❌ Parses localStorage on every render, then ignores the result
const [todos, setTodos] = useState(JSON.parse(localStorage.getItem('todos') ?? '[]'));
// ✅ Runs once
const [todos, setTodos] = useState(() => JSON.parse(localStorage.getItem('todos') ?? '[]'));
106. When should you use useReducer instead of useState?
| Use useState when | Use useReducer when |
|---|---|
| State is a few independent values | Several values change together |
| Updates are simple assignments | Next state depends on rules (a state machine) |
| Logic is local to one handler | Many handlers update the same state |
| – | You want to test transitions without rendering |
107. Show a useReducer example.
function reducer(state, action) {
switch (action.type) {
case 'fetch': return { status: 'loading', data: state.data, error: null };
case 'success': return { status: 'success', data: action.data, error: null };
case 'failure': return { status: 'error', data: null, error: action.error };
default: throw new Error(`Unknown action: ${action.type}`);
}
}
let state = { status: 'idle', data: null, error: null };
state = reducer(state, { type: 'fetch' });
state = reducer(state, { type: 'success', data: [1, 2] });
console.log(state.status, state.data); // "success" [1, 2]
In a component: const [state, dispatch] = useReducer(reducer, initialState). The reducer is a pure function, so you can unit test it without React.
108. What is useRef used for?
useRef returns a mutable object, { current: initialValue }, that persists across renders. Changing .current doesn’t trigger a re-render. Two main uses:
- DOM access: focus an input, measure an element, scroll into view.
- Instance variables: timer ids, the previous value, the latest callback, an AbortController.
109. useRef vs useState: what’s the difference?
| Aspect | useState | useRef |
|---|---|---|
| Triggers re-render on change | Yes | No |
| Value during render | Snapshot for that render | Whatever .current is right now |
| Use for | Anything shown on screen | Data that doesn’t affect output |
Rule of thumb: if the value appears in the JSX, it’s state.
110. Why shouldn’t you read or write ref.current during render?
Refs are escape hatches outside React’s data flow. Reading one during render makes output depend on a value React doesn’t track, so the UI can show stale data. Writing one during render is a side effect that breaks purity, and concurrent rendering may run your component several times.
Read and write refs in event handlers and effects. The one accepted exception is lazily initializing a ref: if (ref.current === null) ref.current = new Thing().
111. How do you get the previous value of a prop or state?
The classic usePrevious hook stores the value in a ref after each commit:
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
Know its limit for senior rounds: it reads a ref during render, so it returns the value from the previous commit, and it’s exactly the pattern the React docs discourage. If you only need to react to a change, the “store previous value in state” pattern from question 98 is the documented alternative. Practice a related hook: useLastDistinct.
112. What is useId for?
useId generates a unique, stable id that matches between server and client rendering. Use it to connect labels and inputs, or aria-describedby targets, in reusable components.
function EmailField() {
const id = useId();
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
</>
);
}
Don’t use it for list keys. Keys should come from your data.
113. What does useImperativeHandle do?
It customizes what a parent receives through a ref. Instead of exposing the whole DOM node, the child exposes a small API.
function VideoPlayer({ ref, src }) {
const videoRef = useRef(null);
useImperativeHandle(ref, () => ({
play: () => videoRef.current.play(),
pause: () => videoRef.current.pause(),
}), []);
return <video ref={videoRef} src={src} />;
}
Use it sparingly, for imperative actions like focus, play, or scroll. If you can express it as a prop (isPlaying), do that instead.
114. What is forwardRef, and what changed in React 19?
Before React 19, a function component couldn’t receive a ref prop; you had to wrap it in forwardRef((props, ref) => ...). In React 19, ref is a regular prop for function components, so you can destructure it directly (as in question 113). forwardRef still works but is on its way to deprecation.
115. Where do you store a timer or interval id in a component?
In a ref. It needs to survive re-renders (so not a local variable) and changing it shouldn’t re-render (so not state).
const timerRef = useRef(null);
function start() {
clearInterval(timerRef.current);
timerRef.current = setInterval(tick, 1000);
}
function stop() {
clearInterval(timerRef.current);
}
useEffect(() => () => clearInterval(timerRef.current), []); // clear on unmount
Practice: Lap Split Stopwatch and Wall Clock.
116. What built-in hooks does React have?
| Category | Hooks |
|---|---|
| State | useState, useReducer |
| Context | useContext (and use in React 19) |
| Refs | useRef, useImperativeHandle |
| Effects | useEffect, useLayoutEffect, useInsertionEffect, useEffectEvent |
| Performance | useMemo, useCallback, useTransition, useDeferredValue |
| Forms and actions (19) | useActionState, useOptimistic, useFormStatus (react-dom) |
| Other | useId, useSyncExternalStore, useDebugValue |
useDebugValue adds a label to a custom hook in React DevTools. useInsertionEffect is for CSS-in-JS library authors to inject styles before layout effects run.
117. What is useSyncExternalStore?
It subscribes a component to an external data source (a store, a browser API) in a way that’s safe with concurrent rendering. You give it a subscribe function and a getSnapshot function.
function subscribe(callback) {
window.addEventListener('resize', callback);
return () => window.removeEventListener('resize', callback);
}
function useWindowWidth() {
return useSyncExternalStore(subscribe, () => window.innerWidth, () => 1024);
}
The third argument is the server snapshot, used during SSR and hydration. Practice: useViewportSize.
118. Do two components using the same custom hook share state?
No. A custom hook shares logic, not state. Each call creates its own state, exactly as if the component had called useState directly. To share state, lift it up, put it in context, or use an external store.
119. When should a function be a custom hook versus a plain function?
Only when it calls other hooks. A function like formatDate or sortByName that uses no hooks should be a plain function, named without the use prefix, so it can be called anywhere (including conditionally and outside components).
Naming something useX tells readers and the linter that the rules of hooks apply.
120. Is the dispatch function from useReducer stable?
Yes. Like the useState setter, dispatch keeps the same identity for the component’s lifetime. You can pass it to memoized children or context without causing re-renders, and you can omit it from effect dependencies (the linter knows this).
A common pattern is to put dispatch in its own context and state in another, so components that only send actions never re-render on state changes.
121. How would you implement a useToggle hook?
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((v) => !v), []);
return [on, toggle, setOn];
}
Small details interviewers check: the updater form (so rapid toggles don’t read stale state), and a stable toggle reference. Practice: useFlag and useCycle.
122. Implement a useLocalStorage hook.
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
Follow-ups to expect: SSR (no localStorage on the server, so read it in an effect or guard with typeof window), syncing across tabs with the storage event, and quota errors on write.
123. Implement useInterval without stale closures.
The naive version captures the callback from the first render, so it reads stale state. Store the latest callback in a ref and keep the interval itself stable:
function useInterval(callback, delay) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay === null) return;
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
Passing null pauses it. In React 19.2+, useEffectEvent replaces the ref pattern (see question 145). Practice: useHeartbeat.
124. What is a callback ref?
Instead of a ref object, you pass a function to ref. React calls it with the DOM node when it attaches and, before React 19, with null when it detaches. Use it when you need to run code the moment a node appears, such as measuring it.
<div ref={(node) => {
if (!node) return;
const observer = new ResizeObserver(() => setHeight(node.offsetHeight));
observer.observe(node);
return () => observer.disconnect(); // React 19: cleanup function
}} />
React 19 lets callback refs return a cleanup function, like effects. One catch: an inline callback is a new function every render, so React detaches and re-attaches it each time. Wrap it in useCallback when the setup is expensive.
125. How do you share a ref between your component and a parent?
Merge them: attach your own ref and forward the node to the parent’s ref, which might be an object or a callback.
function Input({ ref, ...props }) {
const localRef = useRef(null);
const setRefs = (node) => {
localRef.current = node;
if (typeof ref === 'function') ref(node);
else if (ref) ref.current = node;
};
return <input ref={setRefs} {...props} />;
}
This comes up when building component libraries, where you need the node internally (for focus management) and consumers also want it.
useEffect and Side Effects

Find in-depth explanations and practice here: useEffect vs useLayoutEffect ->
useEffect causes more React bugs than any other API, so interviewers ask about it in every round. The strongest candidates explain it as synchronization with an external system, not as lifecycle methods.
126. Explain useEffect.
Most people say “it’s for side effects” or “it’s like componentDidMount”. Both are incomplete.
A better answer: useEffect synchronizes your component with something outside React (a subscription, a timer, the document title, a network request). It runs after the browser paints. When dependencies change, React runs the previous effect’s cleanup, then the new effect. On unmount, it runs the cleanup.
useEffect(() => {
document.title = `${unread} unread messages`;
}, [unread]);
127. What does the dependency array control?
| Dependency array | Effect runs |
|---|---|
| Omitted | After every render |
[] |
After the first render only (plus cleanup on unmount) |
[a, b] |
After the first render and whenever a or b changes (by Object.is) |
The dependency array isn’t a choice you make. It must list every reactive value the effect reads (props, state, and anything derived from them). The linter tells you what’s missing.
128. When does the cleanup function run?
Before the effect runs again (with the old values), and once when the component unmounts. In development with StrictMode, React also runs one extra setup-cleanup cycle on mount to check that your cleanup actually undoes the setup.
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect(); // runs before reconnecting to a new room
}, [roomId]);
129. useEffect vs useLayoutEffect: when do you use each?
useLayoutEffect runs after React updates the DOM but before the browser paints. Use it when you need to measure the DOM and adjust before the user sees anything, such as positioning a tooltip. Otherwise, use useEffect, because layout effects block painting.
useLayoutEffect(() => {
const { height } = tooltipRef.current.getBoundingClientRect();
setTop(anchorTop - height - 8); // no visible flicker
}, [anchorTop]);
Layout effects don’t run during server rendering, which is another reason to default to useEffect.
130. Why shouldn’t you leave values out of the dependency array?
The effect keeps the values from the render where it last ran. If you omit userId, the effect keeps fetching the first user forever, with no error to tell you. That’s a stale closure bug.
If adding a dependency makes the effect run too often, the fix is to change the code so the effect doesn’t need that value (move it inside the effect, use an updater function, or use useEffectEvent), not to silence the linter.
131. Why do objects and functions in the dependency array cause infinite loops?
An object or function created during render is a new reference every render. The effect sees a “changed” dependency every time, runs, maybe sets state, re-renders, and repeats.
// ❌ options is a new object every render
const options = { roomId, serverUrl };
useEffect(() => { connect(options); }, [options]);
// ✅ Depend on primitives; build the object inside the effect
useEffect(() => {
connect({ roomId, serverUrl });
}, [roomId, serverUrl]);
Other fixes: move constants outside the component, or memoize with useMemo / useCallback when the object must be shared.
132. How do you fetch data in useEffect correctly?
Handle the race condition. If userId changes quickly, an older request can resolve after a newer one and overwrite the UI with the wrong user.
useEffect(() => {
const controller = new AbortController();
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((r) => r.json())
.then(setUser)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => controller.abort(); // stale request can't overwrite the new user
}, [userId]);
Mention the race condition this prevents, and you’ve turned a basic question into a senior answer.
133. Why can’t the useEffect callback be async?
An async function always returns a promise, but React expects the effect to return either nothing or a cleanup function. Define an async function inside the effect and call it:
useEffect(() => {
let ignore = false;
async function load() {
const res = await fetch(`/api/items?q=${query}`);
const data = await res.json();
if (!ignore) setItems(data);
}
load();
return () => { ignore = true; };
}, [query]);
The ignore flag is the simplest race-condition guard when you can’t abort the request.
134. When don’t you need an effect?
The React docs have a whole page on this, and interviewers know it. You don’t need an effect to:
- Transform data for rendering: compute it during render (filtered lists, totals).
- Respond to a user event: do it in the event handler (submit a form, show a toast).
- Reset state when a prop changes: use a
key. - Notify a parent about a change: call the parent’s callback in the same handler that changed the state.
- Cache an expensive calculation: use
useMemo.
Effects are for synchronizing with systems outside React. If there’s no external system, there’s probably no need for an effect.
135. Should this code go in an event handler or an effect?
Ask why the code runs. If it runs because the user did something (clicked Buy), it belongs in the handler. If it runs because the component is visible on screen with certain values (connected to a chat room while the room is open), it belongs in an effect.
// ✅ Handler: caused by a specific interaction
function handleBuy() { post('/api/buy', { productId }); showToast('Added!'); }
// ✅ Effect: caused by displaying the component
useEffect(() => { logImpression(productId); }, [productId]);
136. How do you run an effect only once?
Use an empty dependency array, and only if the effect truly reads no reactive values. In development, StrictMode will still run it twice (setup, cleanup, setup), so the effect must be safe to repeat.
For code that must run once per app load, not per mount (initializing an SDK), put it at module level or behind a module-level flag, outside any component.
137. How do you add a window event listener in a component?
useEffect(() => {
function onKeyDown(e) {
if (e.key === 'Escape') onClose();
}
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [onClose]);
Remove the exact same function reference you added, or the listener leaks. If onClose changes every render, the listener is re-added every render; a stable callback or useEffectEvent fixes that. Practice: useDomEvent and useDismiss.
138. Why does this effect cause an infinite loop?
useEffect(() => {
setCount(count + 1);
}, [count]);
The effect updates count, which triggers a render, which changes count, which re-runs the effect. An effect that sets state it also depends on needs a condition that eventually stops it, or (more often) shouldn’t be an effect at all.
139. How do you debounce a value with hooks?
function useDebouncedValue(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id); // a new keystroke cancels the pending update
}, [value, delay]);
return debounced;
}
The cleanup is the whole trick: every change cancels the previous timer. Solve it in the editor: useDebouncedValue, then useThrottledValue.
140. What’s wrong with chaining effects?
An effect chain is effect A setting state that triggers effect B, which sets state that triggers effect C. Each link adds a render, the flow is hard to follow, and intermediate renders show inconsistent UI.
Compute what you can during render, and do the rest in the event handler that started the change. One handler that calculates the full next state beats three effects reacting to each other.
141. How would you keep a component connected to a chat room?
function ChatRoom({ roomId }) {
const [messages, setMessages] = useState([]);
useEffect(() => {
const socket = new WebSocket(`wss://chat.example.com/rooms/${roomId}`);
socket.onmessage = (e) => setMessages((prev) => [...prev, JSON.parse(e.data)]);
return () => socket.close();
}, [roomId]);
return <MessageList messages={messages} />;
}
Points to call out: the updater form avoids a stale messages closure, the cleanup closes the old socket when the room changes, and you’d probably reset messages on room change with a key on ChatRoom. See the full design in Design Chat App.
142. When does useEffect run relative to painting?
Usually after the browser paints, so effects don’t delay what the user sees. One exception: if the effect was caused by a user interaction such as a click, React may run it before paint so the result of that interaction is visible right away. Either way, effects never block the commit.
143. In what order do parent and child effects run?
Children first. React commits the tree bottom-up, so a child’s effects run before its parent’s. Cleanups run in the same child-before-parent order on unmount. This is why a parent’s effect can safely assume its children’s DOM nodes and refs are ready.
144. How do you avoid stale closures in effects?
- List every dependency, so the effect re-subscribes with fresh values.
- Use updater functions (
setCount(c => c + 1)) so the effect doesn’t need the current state. - Move functions that the effect uses inside the effect.
- Read “latest value without re-running” through a ref or
useEffectEvent.
145. What is useEffectEvent?
useEffectEvent (stable since React 19.2) creates a function that always sees the latest props and state, but isn’t reactive: it doesn’t belong in the dependency array and changing what it reads doesn’t re-run the effect.
function ChatRoom({ roomId, theme }) {
const onConnected = useEffectEvent(() => {
showNotification('Connected!', theme); // reads latest theme
});
useEffect(() => {
const connection = createConnection(roomId);
connection.on('connected', () => onConnected());
connection.connect();
return () => connection.disconnect();
}, [roomId]); // changing theme doesn't reconnect
}
Only call effect events from inside effects. They replace the “latest callback in a ref” pattern from question 123.
146. How do you skip an effect on the first render?
You can track it with a ref (isFirstRender.current), but it’s usually a sign the code belongs elsewhere. “Save when the value changes, but not on mount” is really “save when the user edits”, which is an event handler. Also note that StrictMode’s double mount breaks naive first-render flags.
147. Is it okay to send analytics from an effect?
Yes, for impressions: “this page or item was shown” is caused by displaying the component, which is what effects model. In development StrictMode it fires twice; that’s expected and doesn’t happen in production. For “the user clicked X” events, log in the click handler instead.
148. What happened to the “state update on an unmounted component” warning?
React 18 removed it. It was usually a false alarm (a fetch resolving after unmount isn’t a leak), and it pushed people toward isMounted hacks. You should still cancel subscriptions, timers, and requests in cleanup, because those are real leaks and real race conditions.
149. Do effects run during server-side rendering?
No. Neither useEffect nor useLayoutEffect runs on the server; they run after hydration in the browser. That makes effects the right place for browser-only APIs (window, localStorage, matchMedia), and it’s why reading those during render causes hydration mismatches.
150. Why do teams use a data-fetching library instead of fetching in useEffect?
Fetching in effects works, but you rebuild the same things in every component: caching, deduplicating identical requests, retries, refetching on focus or reconnect, pagination, race conditions, and loading and error state. Effects also start fetching only after render, which creates network waterfalls.
TanStack Query, SWR, or your framework’s loaders (Next.js, React Router) solve these once. In interviews, write the effect version to show you understand it, then say what you’d use in production and why. See Server State vs Client State.
Performance and Memoization

Find in-depth explanations and practice here: Frontend Performance Optimizations ->
Performance questions reward process over tricks. Interviewers want to hear “I’d measure first” before any mention of useMemo.
151. How would you speed up a slow React app?
- Reproduce and measure in a production build with the React DevTools Profiler and the browser Performance panel.
- Find the cause: an expensive component, too many re-renders, a huge list, a big bundle, or slow network requests.
- Apply the cheapest fix: move state down, lift content up as children, then memoize, virtualize, split code, or defer work with a transition.
- Measure again to confirm it helped.
Saying “I’d wrap everything in useMemo” without measuring is the answer that loses points.
152. What does React.memo do?
React.memo(Component) skips re-rendering the component when its props are shallowly equal to the previous props. It’s useful for components that are expensive to render and often receive the same props.
const Chart = memo(function Chart({ data, color }) {
// expensive SVG rendering
});
You can pass a custom comparison function as the second argument, but it’s rarely worth the complexity.
153. When does React.memo not help?
- When a prop is a new object, array, or function every render (
style={{...}},onClick={() => ...}), so the shallow comparison always fails. - When the component reads a context that changes.
- When it receives
childrenas JSX, which is a new element each render. - When the component is cheap; the comparison then costs about as much as rendering.
154. What does useMemo do?
useMemo(fn, deps) caches the result of a calculation between renders and recomputes it only when a dependency changes.
const visibleTodos = useMemo(
() => filterTodos(todos, tab), // expensive with thousands of items
[todos, tab]
);
React may discard the cache (for example, for offscreen components), so treat it as a performance hint, never as a guarantee your code depends on for correctness.
155. What does useCallback do?
useCallback(fn, deps) returns the same function reference between renders until a dependency changes. It’s useMemo(() => fn, deps) for functions.
It only helps when something cares about the function’s identity: a React.memo child that receives it, or an effect or hook that lists it as a dependency. On its own, it doesn’t make anything faster.
156. When should you use useMemo and useCallback?
Not everywhere. That’s the answer interviewers want to hear first.
useMemo: when a calculation is genuinely expensive, or when you need a stable object reference for a memoized child or an effect dependency.useCallback: when passing a function to aReact.memochild or using it as an effect dependency.
Memoization isn’t free. It costs memory and a dependency comparison on every render. Wrapping everything makes code harder to read and often doesn’t help.
157. React.memo vs useMemo vs useCallback: what’s the difference?
| API | Memoizes | Used where |
|---|---|---|
| React.memo | A component’s render output | Around a component definition |
| useMemo | A computed value | Inside a component |
| useCallback | A function reference | Inside a component |
They’re often used together: useCallback keeps a handler stable so the React.memo child it’s passed to can skip rendering.
158. What is the React Compiler?
The React Compiler is a build-time tool (stable since late 2025) that automatically memoizes components and values. It analyzes your code and inserts the equivalent of React.memo, useMemo, and useCallback where they’re safe and useful.
It only works if your code follows the rules of React: pure render, no mutation of props or state, and hooks called correctly. Code that breaks the rules is skipped, which is one more reason to follow them.
159. With the React Compiler, do you still need useMemo and useCallback?
Mostly not for new code. The compiler handles the common cases more precisely than people do by hand. Manual memoization still matters in codebases without the compiler, as an escape hatch when you need an exact guarantee (an effect dependency that must stay stable), and in interviews, where you’re expected to explain how it works.
160. How do you render a list of 10,000 items efficiently?
Virtualize it: render only the rows visible in the viewport plus a small buffer, and use spacer elements to keep the scrollbar size correct. Libraries such as TanStack Virtual and react-window do this.
Follow-ups to expect: variable row heights (measure and cache), keeping keyboard focus and screen reader access, and preserving scroll position. Deep dives: List Virtualization and Virtualizing Variable-Height Lists.
161. How do you reduce the initial bundle size?
- Split by route with
React.lazyor your framework’s automatic route splitting. - Lazy-load heavy, rarely used components (editors, charts, maps) when they’re needed.
- Check what’s in the bundle with an analyzer, and replace heavy dependencies (a full date library for one format call).
- Import only what you use so tree shaking can remove the rest.
- Move rendering to the server with Server Components, which ship no JavaScript for non-interactive parts.
162. How do you keep a search input fast when filtering a big list?
Separate the urgent update (the input’s value) from the expensive one (the filtered list). Three options, from oldest to newest:
- Debounce the filter so it runs after the user pauses typing.
- useDeferredValue to render the list with a slightly older query while the input stays responsive.
- startTransition to mark the list update as interruptible.
Debounce reduces work; transitions keep the input responsive while the work happens. For network requests, debounce is still the right tool. See Debounce vs Throttle.
163. What does useTransition do?
useTransition marks a state update as non-urgent. React renders it in the background and can interrupt it if a more urgent update (like typing) comes in. It also gives you an isPending flag.
const [isPending, startTransition] = useTransition();
function selectTab(next) {
startTransition(() => setTab(next)); // a slow tab won't freeze the UI
}
It doesn’t make the slow render faster. It keeps the page responsive while the slow render happens.
164. What does useDeferredValue do?
useDeferredValue(value) returns a copy of the value that “lags behind” during urgent updates. React first re-renders with the old deferred value, then renders again in the background with the new one.
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<SlowResults query={deferredQuery} />
</div>
Use it when you don’t control the state update (the value comes from props); use useTransition when you do. SlowResults must be wrapped in memo for this to help.
165. How do you handle CPU-heavy work without freezing the UI?
Move it off the main thread with a Web Worker (parsing a large file, image processing, complex calculations), and post the result back to set state. For work that must stay on the main thread, split it into chunks and yield between them (scheduler.yield() where supported, or setTimeout), or mark the resulting render as a transition.
166. How do you optimize images in a React app?
- Serve modern formats (WebP, AVIF) at the right size with
srcsetandsizes. - Lazy-load below-the-fold images with
loading="lazy", but never the LCP image. - Set
widthandheight(oraspect-ratio) to prevent layout shift. - Give the hero image
fetchpriority="high".
Framework image components (next/image) automate most of this. Deep dive: Image Optimization Strategies.
167. Why is typing in one input re-rendering the whole form?
Because the input’s state lives in a component high up, so every keystroke re-renders everything below it. Move the state down into the input (or a small component around it), and lift it up only when the value is needed, such as on submit.
For large forms, uncontrolled inputs with a library such as React Hook Form avoid re-rendering on every keystroke entirely.
168. How do you stop a context provider from re-rendering every consumer?
First, make sure the value doesn’t change when nothing changed. An inline object is new every render:
// ❌ New object every render of AuthProvider: every consumer re-renders
<AuthContext.Provider value={{ user, login, logout }}>
// ✅ Stable until user changes
const value = useMemo(() => ({ user, login, logout }), [user, login, logout]);
<AuthContext.Provider value={value}>
Then split contexts by how often they change (state vs actions), or move fast-changing values to a store with selectors.
169. Why is my app slower in development than in production?
Development builds include extra checks, warnings, and StrictMode double rendering, and they aren’t minified. Never profile performance in development mode for final decisions. Use a production build (React DevTools supports profiling builds) to measure real-world numbers.
170. What is the Profiler component?
<Profiler id="Sidebar" onRender={callback}> measures how often a subtree renders and how long it takes, programmatically. The callback receives the phase (mount or update) and the actual and base durations.
It’s useful for tracking render performance in automated tests or in production monitoring (with a profiling build). For day-to-day debugging, the DevTools Profiler is easier.
171. How does React affect Core Web Vitals?
| Metric | React-related cause | Fix |
|---|---|---|
| LCP | Content waits for JavaScript to render | SSR or SSG, preload the hero image |
| INP | Long renders block input handling | Transitions, smaller components, less work per event |
| CLS | Content pops in after data loads | Reserve space, use skeletons with fixed size |
Deep dive: Core Web Vitals.
172. Do inline arrow functions in JSX hurt performance?
Almost never by themselves. Creating a function is cheap. They only matter when passed to a memoized child (breaking its React.memo) or listed as an effect dependency. Don’t wrap every handler in useCallback “just in case”; fix it where a profile shows it matters.
173. How do keys affect list performance?
Stable keys let React move existing DOM nodes when items are reordered, instead of destroying and recreating them. Unstable keys (random values, or indexes in a reordered list) force React to remount rows, which is slow and loses state. Good keys are a performance fix and a correctness fix at the same time.
174. How do you find what’s making the bundle large?
Run a bundle analyzer (rollup-plugin-visualizer for Vite, @next/bundle-analyzer for Next.js) and look for large dependencies, duplicated packages, and code that should have been split. Then check each import: a lodash import that pulls the whole library, a moment.js locale bundle, or an icon pack imported in full are common culprits.
175. What is an “expensive” render, and how do you confirm it?
A rule of thumb: anything that pushes an interaction past one frame (about 16ms at 60fps), or makes an interaction take more than 200ms total (the INP “good” threshold). Confirm with the Profiler’s flame graph, which shows each component’s render time, and wrap suspicious calculations in console.time to measure them directly. If a component renders in under a millisecond, memoizing it won’t change anything users can feel.
Context and State Management

Find in-depth explanations and practice here: React Context and the Provider Pattern ->
State management questions are really “where should this data live?” questions. The best answers sort state by type before naming any library.
176. What is the Context API?
Context lets a parent make a value available to every component below it without passing props through each level. You create a context, provide a value high in the tree, and read it anywhere below with useContext.
It solves prop drilling for values many components need, such as the theme, locale, or current user.
177. How do you create and use a context?
const ThemeContext = createContext('light');
function App() {
const [theme, setTheme] = useState('dark');
return (
<ThemeContext value={theme}> {/* React 19; earlier: <ThemeContext.Provider> */}
<Toolbar />
</ThemeContext>
);
}
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Save</button>;
}
React 19 lets you render the context itself as the provider, and the new use(ThemeContext) API can read context conditionally, which useContext can’t.
178. When should you use context?
For data that many components at different depths need, and that changes infrequently: theme, locale, authenticated user, feature flags, or a design system’s configuration. It’s also the standard way to share state inside compound components.
Before reaching for it, check whether passing children (composition) removes the drilling. It often does.
179. Is context a state management tool?
No. Context is a transport mechanism: it moves a value down the tree. The state still lives in useState or useReducer in the provider component. Context plus useReducer can work as lightweight state management, but it lacks selectors, so every consumer re-renders on every change.
180. Context vs Redux: how do you choose?
| Aspect | Context + useReducer | Redux Toolkit |
|---|---|---|
| Setup | Built in, no dependency | A library and a store |
| Re-renders | All consumers on any change | Only components whose selected data changed |
| DevTools | React DevTools only | Action log, time travel |
| Best for | Low-frequency, app-wide values | Large, frequently updated shared state |
181. What is Redux, and what are its core principles?
Redux is a predictable state container. Its three principles:
- Single source of truth: the global state lives in one store.
- State is read-only: the only way to change it is to dispatch an action (a plain object describing what happened).
- Changes are pure functions: reducers take the previous state and an action and return the next state.
The payoff is traceability: every change is a logged action you can replay.
182. What is Redux Toolkit, and why use it?
Redux Toolkit (RTK) is the official, recommended way to write Redux. It removes the boilerplate that gave Redux its reputation:
createSlicegenerates action creators and reducers together.- Immer lets you write “mutating” update logic safely.
configureStoresets up DevTools and sensible middleware.- RTK Query handles data fetching and caching.
import { createSlice } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState: { items: [] },
reducers: {
added(state, action) {
state.items.push(action.payload); // Immer makes this immutable
},
},
});
export const { added } = cartSlice.actions;
183. What are selectors, and why memoize them?
A selector is a function that reads a piece of the store: state => state.cart.items. Components subscribe through selectors, so they re-render only when the selected value changes.
Selectors that derive new arrays or objects (items.filter(...)) return a new reference every time, causing re-renders. createSelector (Reselect) memoizes them so the result is reused until the inputs change.
184. Zustand vs Redux Toolkit?
Zustand is a small store with a hook-based API and almost no setup: you create a store with state and actions, then select from it in components. Redux Toolkit is more structured, with actions, middleware, and stronger DevTools.
I’d pick Zustand for small-to-medium client state, and Redux Toolkit for large teams that benefit from enforced conventions and an action log. Both use useSyncExternalStore and selector-based subscriptions.
185. What is a thunk, and why is middleware needed?
Reducers must be pure and synchronous, so async work (API calls) can’t go in them. Middleware sits between dispatching an action and the reducer, and can run side effects. A thunk is a function you dispatch instead of an object; the thunk middleware calls it with dispatch and getState, so it can fetch data and dispatch results. RTK’s createAsyncThunk generates the pending, fulfilled, and rejected actions for you.
186. What’s the difference between server state and client state?
Client state is owned by the browser: whether a modal is open, the current theme, form drafts. Server state is a cached copy of data owned by the server: users, products, messages. Server state can go stale, be shared by other users, and needs refetching, deduplication, and invalidation.
The key insight interviewers want: most “global state” is actually server cache, and putting it in a data-fetching cache (TanStack Query, SWR) instead of Redux removes a lot of code. More in Server State vs Client State.
187. What are the core ideas of TanStack Query?
- Query keys identify cached data:
['user', userId]. - Stale time decides how long data counts as fresh before a background refetch.
- Automatic refetching on window focus, reconnect, and mount (configurable).
- Mutations change server data, then invalidate related queries so they refetch.
- Deduplication: ten components asking for the same key make one request.
const { data, isPending, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then((r) => r.json()),
staleTime: 60_000,
});
188. How would you manage state in a large app?
| Kind of state | Where I’d put it |
|---|---|
| Local UI state (open, hover, input value) | useState in the component |
| Shared by a few nearby components | Lift it to the closest common parent |
| Rarely changing app-wide values (theme, user, locale) | Context |
| Server data (lists, details) | A data-fetching cache (TanStack Query, SWR) |
| Complex, frequently changing shared client state | A store (Redux Toolkit, Zustand) |
| Shareable state (filters, tabs, pagination) | The URL |
Also mention that context isn’t a performance-friendly store for fast-changing values, because every consumer re-renders when the value changes.
189. When should state live in the URL?
When a user would expect to share, bookmark, or go back to it: search queries, filters, sort order, pagination, the selected tab, an open item’s id. Putting it in the URL gives you deep links, working back and forward buttons, and state that survives a refresh, for free.
const [searchParams, setSearchParams] = useSearchParams(); // React Router
const sort = searchParams.get('sort') ?? 'newest';
setSearchParams({ sort: 'price' });
190. How do you split context to avoid unnecessary re-renders?
Split by change frequency and by reader. A common split is one context for state and one for actions (the dispatch function or memoized callbacks never change, so action-only components never re-render).
const TodosContext = createContext(null);
const TodosDispatchContext = createContext(null);
function TodosProvider({ children }) {
const [todos, dispatch] = useReducer(todosReducer, []);
return (
<TodosContext value={todos}>
<TodosDispatchContext value={dispatch}>{children}</TodosDispatchContext>
</TodosContext>
);
}
More patterns in Avoiding Context Re-render Pitfalls.
191. What is the default value in createContext for?
It’s what useContext returns when there’s no matching provider above the component. It’s useful for tests and for contexts with sensible defaults (a light theme). For contexts that must have a provider (auth, a store), pass null and throw a clear error in a custom hook.
192. How do you write a safe custom hook for a context?
const AuthContext = createContext(null);
export function useAuth() {
const ctx = useContext(AuthContext);
if (ctx === null) {
throw new Error('useAuth must be used inside <AuthProvider>');
}
return ctx;
}
Consumers never touch the raw context, you get a clear error instead of “cannot read property of null”, and you can change the implementation later without touching call sites.
193. What is an optimistic update?
You update the UI immediately as if the server request succeeded, then roll back if it fails. It makes actions such as likes, upvotes, and reordering feel instant.
Implementation steps: save the previous state, apply the change, send the request, and restore the snapshot on error (with a message to the user). TanStack Query supports it in mutations, and React 19 adds useOptimistic (question 248). Practice: Optimistic Upvote Button.
194. What does normalizing state mean?
Storing entities by id in lookup tables instead of nesting them, the way a database would. Each item exists in one place, so an update happens once and every view sees it.
const state = {
posts: { byId: { p1: { id: 'p1', authorId: 'u1' } }, allIds: ['p1'] },
users: { byId: { u1: { id: 'u1', name: 'Ada' } } },
};
const post = state.posts.byId.p1;
console.log(state.users.byId[post.authorId].name); // "Ada"
RTK’s createEntityAdapter and GraphQL clients’ caches normalize for you. See Normalization.
195. What is atomic state management?
Libraries such as Jotai model state as small independent pieces (“atoms”) that components subscribe to individually. Derived atoms compute from other atoms. Only components reading a changed atom re-render, so you get fine-grained updates without writing selectors. It suits UIs with many independent pieces of state, such as editors and design tools.
196. What are signals, and does React use them?
Signals are reactive values that track who reads them and update only those readers directly, without re-running whole components. Solid, Preact, Vue, and Angular use them.
React doesn’t. It re-renders components and relies on memoization (now automated by the React Compiler) to skip unchanged work. Knowing this trade-off (signals: fine-grained updates; React: simpler mental model of UI as a function of state) is a good senior talking point.
197. How do you persist state across page reloads?
Write it to storage and read it back on startup: localStorage for small, synchronous data (preferences), IndexedDB for larger or structured data (drafts, offline caches). Stores have plugins (Zustand’s persist middleware, redux-persist), and TanStack Query can persist its cache.
Version what you store, so a schema change doesn’t crash the app on old data, and never persist secrets or tokens in localStorage. See IndexedDB.
198. How do you sync state across browser tabs?
- The
storageevent fires in other tabs whenlocalStoragechanges. BroadcastChannelsends messages between tabs of the same origin, for any data.
Typical uses are logging out everywhere, or keeping a cart in sync. Deep dive: Broadcast Channels.
199. How do you organize state code in a large codebase?
By feature, not by type. Each feature folder owns its components, hooks, store slice or queries, and types. Shared state gets a small, explicit public API (hooks like useCart()), and components never reach into another feature’s internals. Separating view components from the hooks that hold logic (a view-model) keeps both testable. See MVVM in React and Layered Frontend Architecture.
200. How would you choose state management for a new app?
Start with the defaults and add tools only for real problems:
- Local state and lifting state up.
- A data-fetching library or framework loaders for all server data.
- The URL for shareable UI state.
- Context for a few app-wide, low-frequency values.
- A store (Zustand or Redux Toolkit) only when shared client state is complex and changes often.
Interviewers care less about the library you pick than about whether you can explain why.
Forms, Events, and Refs

Find in-depth explanations and practice here: Signup Form ->
Forms show up constantly in UI coding rounds. Expect to build one, validate it, and explain your controlled vs uncontrolled choice.
201. Controlled vs uncontrolled components: what’s the difference?
Controlled: React state is the source of truth, and the input’s value comes from props. Uncontrolled: the DOM holds the value, and you read it with a ref or from the form when needed.
// Controlled
<input value={name} onChange={(e) => setName(e.target.value)} />
// Uncontrolled
<input defaultValue="Ada" ref={nameRef} />
Controlled is easier for instant validation and dependent fields. Uncontrolled can be simpler and faster for big forms. Saying “it depends, here’s the trade-off” is better than picking one as always right.
202. How do you handle a form submission in React?
Handle onSubmit on the <form>, not onClick on the button, so pressing Enter works. Call e.preventDefault() to stop the full page reload.
function handleSubmit(e) {
e.preventDefault();
const data = Object.fromEntries(new FormData(e.currentTarget));
save(data);
}
<form onSubmit={handleSubmit}>
<input name="email" type="email" required />
<button type="submit">Subscribe</button>
</form>
FormData reads every named field, which keeps uncontrolled forms short.
203. How do you handle many inputs with one change handler?
Give each input a name matching a key in state and use a computed property name:
const [form, setForm] = useState({ firstName: '', lastName: '', email: '' });
function handleChange(e) {
const { name, value } = e.target;
setForm((prev) => ({ ...prev, [name]: value }));
}
<input name="firstName" value={form.firstName} onChange={handleChange} />
204. How would you validate a form?
- Use native constraints first (
required,type="email",minLength,pattern). They’re free and accessible. - Define the rules once in a schema (Zod) and reuse it on the server.
- Validate on blur or on submit, not on every keystroke, so users aren’t shown errors while still typing.
- Show errors next to the field, link them with
aria-describedby, setaria-invalid, and move focus to the first invalid field on submit.
Client-side validation is for user experience. The server must validate again. Practice: Support Ticket Form and useField.
205. Why use a form library like React Hook Form?
Large controlled forms re-render on every keystroke and need a lot of glue code for touched state, errors, and submission. React Hook Form uses uncontrolled inputs with refs, so typing doesn’t re-render the form, and it handles validation (with Zod or Yup resolvers), errors, dirty tracking, and field arrays.
For two or three fields, plain React is fine. For a 30-field settings page, a library saves time and bugs.
206. How do checkboxes, radios, and selects work in React?
| Input | Controlled prop | Read from |
|---|---|---|
| Text, textarea | value | e.target.value |
| Checkbox | checked | e.target.checked |
| Radio group | checked on each radio | e.target.value of the selected one |
| Select | value on the select (not selected on options) | e.target.value |
React normalizes <textarea> and <select> to use value, unlike plain HTML.
207. Why do I get “A component is changing an uncontrolled input to be controlled”?
The input’s value started as undefined (uncontrolled) and later became a string (controlled). It usually happens with useState() with no initial value, or data that hasn’t loaded yet.
// ❌ value is undefined until the user loads
<input value={user?.name} onChange={...} />
// ✅ Always a string
<input value={user?.name ?? ''} onChange={...} />
208. How do you handle file inputs?
File inputs are always uncontrolled, because their value can only be set by the user for security reasons. Read the selected files from e.target.files in onChange, or from a ref. Show previews with URL.createObjectURL(file), and revoke the URL in a cleanup to avoid leaking memory. Practice: Upload Queue.
209. How do you focus an input when a component mounts?
The simplest way is the autoFocus prop. For more control (focus after an animation, or only on desktop), use a ref and an effect:
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
<input ref={inputRef} />
Use auto-focus with care: moving focus unexpectedly disorients screen reader users. It’s appropriate in dialogs and search overlays the user just opened. Practice: useFocusRequest.
210. How do you pass arguments to an event handler?
Wrap it in an arrow function, or read the value from a data attribute:
{items.map((item) => (
<button key={item.id} onClick={() => remove(item.id)}>Remove</button>
))}
By convention, props that receive handlers are named onSomething and the functions are named handleSomething.
211. What’s the difference between stopPropagation and preventDefault?
e.stopPropagation() stops the event from bubbling to parent handlers. e.preventDefault() stops the browser’s default action (following a link, submitting a form) but lets the event keep bubbling. They’re independent, and you sometimes need both.
Avoid stopPropagation as a general fix: it breaks parent handlers you don’t know about, like analytics or “click outside” logic. Background: Propagation.
212. How is React’s onChange different from the native change event?
Native change on a text input fires when the input loses focus after an edit. React’s onChange fires on every keystroke, behaving like the native input event. React chose this so controlled inputs can update state on each change.
213. What was event pooling, and does it still exist?
Before React 17, React reused synthetic event objects for performance, so reading e.target inside a setTimeout or after an await returned null, and you had to call e.persist(). React 17 removed pooling, so events behave like normal objects now. If you see e.persist() in old code, it’s safe to delete.
214. How do you handle keyboard interactions accessibly?
- Use native interactive elements (
<button>,<a href>), which handle Enter and Space for free. - If you must make a custom widget, add
role,tabIndex={0}, and key handlers that match the ARIA pattern (arrow keys in tabs and menus, Escape to close). - Check
e.key('Enter','ArrowDown'), not the deprecatedkeyCode.
Practice: Vertical Keyboard Tabs and useKeyHeld.
215. How do you detect a click outside a component?
function useClickOutside(ref, onOutside) {
useEffect(() => {
function handle(e) {
if (ref.current && !ref.current.contains(e.target)) onOutside();
}
document.addEventListener('pointerdown', handle);
return () => document.removeEventListener('pointerdown', handle);
}, [ref, onOutside]);
}
Follow-ups: content rendered in a portal isn’t a DOM descendant, so contains fails (check the portal node too), and Escape should close the same popover for keyboard users. Practice: useDismiss.
216. How do you measure an element’s size in React?
Read it from a ref after the DOM is ready: getBoundingClientRect() in useLayoutEffect if the measurement affects what you render (to avoid flicker). To react to size changes, use a ResizeObserver and disconnect it in the cleanup. Don’t measure during render; the DOM doesn’t reflect the current render yet.
217. How do you manage focus when content changes?
Move focus deliberately when the user’s context changes: into a dialog when it opens (and back to the trigger when it closes), to the first error after a failed submit, and to the main heading after a client-side route change. Use refs and call focus() in an effect or the handler that caused the change. Practice: Focus-Trapped Dialog.
218. What are form actions in React 19?
In React 19, you can pass a function to a form’s action prop. React calls it with the FormData on submit, runs it in a transition, and resets uncontrolled fields after it succeeds. Paired with useActionState and useFormStatus, you get pending and error state without manual useState plumbing.
async function subscribe(formData) {
await saveEmail(formData.get('email'));
}
<form action={subscribe}>
<input name="email" type="email" />
<SubmitButton />
</form>
With a framework, the action can be a Server Function that runs on the server. Details in the React 19 section.
219. How would you build a multi-step form?
Keep all step data in one parent (state, a reducer, or a form library), and render one step at a time based on a step index. Validate each step before moving forward, keep data when going back, and reflect the step in the URL if users should be able to refresh or share it. Announce step changes and move focus to the new step’s heading for screen reader users.
Practice the logic as a hook: useWizard, then the UI: Sequential Installer Steps.
220. How do you prevent double submission?
Track a pending state, disable the submit button while the request is in flight, and ignore submits while pending. In React 19, useFormStatus or the isPending from useActionState gives you this directly.
function SubmitButton() {
const { pending } = useFormStatus();
return <button type="submit" disabled={pending}>{pending ? 'Saving...' : 'Save'}</button>;
}
The server should still be idempotent (an idempotency key for payments), because disabled buttons don’t stop retries or double clicks on slow networks before the state updates.
Routing, Data Fetching, and Error Handling

Find in-depth explanations and practice here: Data Fetching Strategies ->
These questions sit between React and frontend system design. Strong answers mention loading, error, and empty states without being asked.
221. How does client-side routing work?
The router intercepts link clicks, updates the URL with the History API (history.pushState) without a page reload, and renders the component that matches the new path. It also listens for the popstate event so the back and forward buttons work.
The server must return the app’s HTML for every route (a catch-all), or a refresh on /settings returns a 404.
222. What are the basics of React Router?
const router = createBrowserRouter([
{
path: '/',
element: <Layout />,
children: [
{ index: true, element: <Home /> },
{ path: 'users/:userId', element: <UserPage /> },
],
},
]);
function UserPage() {
const { userId } = useParams();
const navigate = useNavigate();
return <button onClick={() => navigate('/')}>Back from {userId}</button>;
}
Key APIs: route definitions, <Link> for navigation, useParams for path parameters, useSearchParams for the query string, and useNavigate for navigating in code.
223. Why use Link instead of an a tag?
A plain <a href> triggers a full page load, throwing away all React state and re-downloading the app. <Link> renders a real <a> (so it’s accessible, crawlable, and supports open-in-new-tab) but intercepts normal clicks to navigate on the client. Frameworks also prefetch the code for linked routes.
224. How do nested routes and layouts work?
A parent route renders shared UI (navigation, sidebar) and an <Outlet /> where the matched child route appears. Navigating between children keeps the parent mounted, so its state and scroll position survive. Next.js’s App Router does the same with layout.tsx files.
225. How do you protect routes that need authentication?
Check auth before rendering the route and redirect if the user isn’t signed in, preserving where they were going:
function RequireAuth({ children }) {
const { user } = useAuth();
const location = useLocation();
if (!user) return <Navigate to="/login" state={{ from: location }} replace />;
return children;
}
The important caveat: client-side guards are UX only. Anyone can bypass them, so the API must enforce authorization on every request. With a framework, check auth in a loader, middleware, or on the server so protected HTML is never sent.
226. How do you split code by route?
Lazy-load each route’s component so users only download the code for pages they visit. With React Router, use React.lazy or the route’s lazy property; Next.js and other frameworks split by route automatically. Prefetch likely next routes on hover or when the link scrolls into view to hide the delay.
227. What are route loaders, and why do they help?
A loader is a function attached to a route that fetches its data before the route renders (React Router data APIs, Remix-style frameworks). Because the router knows every matched route, it can start all their loaders in parallel as soon as navigation begins, instead of each component fetching after it renders.
{
path: 'users/:userId',
loader: ({ params }) => fetch(`/api/users/${params.userId}`),
element: <UserPage />, // reads the data with useLoaderData()
}
228. What’s the difference between Next.js’s App Router and Pages Router?
| Aspect | Pages Router | App Router |
|---|---|---|
| Components | All client components | Server Components by default |
| Data fetching | getServerSideProps, getStaticProps | async components, fetch with caching options |
| Layouts | _app and manual wrappers | Nested layout files |
| Streaming | Limited | Built in with Suspense and loading files |
The Pages Router is still supported and common in existing codebases; the App Router is where new React features land first.
229. What is a network waterfall, and how do you avoid it?
A waterfall is when requests run one after another even though they could run in parallel. In React it usually happens when a parent fetches, renders a child after the data arrives, and the child then starts its own fetch.
Fixes: fetch independent data in parallel (Promise.all), hoist fetching to route loaders or Server Components, prefetch on hover, and let the server return everything a view needs in one request (a BFF or GraphQL).
230. How does Suspense work for data fetching?
<Suspense fallback={...}> shows a fallback while anything inside it is “suspended”, meaning it’s waiting for code (lazy) or data from a Suspense-enabled source: a framework, TanStack Query’s useSuspenseQuery, or React 19’s use(promise).
<Suspense fallback={<ProfileSkeleton />}>
<Profile userId={id} />
<Suspense fallback={<PostsSkeleton />}>
<Posts userId={id} />
</Suspense>
</Suspense>
Components read data as if it’s already there, and the boundaries decide what loads together. Nested boundaries let the profile show before the posts finish. Suspense doesn’t fetch anything by itself; a plain fetch in an effect won’t trigger it.
231. What is an error boundary?
An error boundary is a component that catches JavaScript errors thrown while rendering its children, and shows a fallback UI instead of unmounting the whole app. It must be a class component with static getDerivedStateFromError (and optionally componentDidCatch for logging), or you can use react-error-boundary.
class ErrorBoundary extends React.Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
logToService(error, info.componentStack);
}
render() {
return this.state.error ? this.props.fallback : this.props.children;
}
}
Place them around independent areas (a widget, a route), so one failure doesn’t blank the page.
232. What errors do error boundaries not catch?
- Errors in event handlers (they don’t happen during render).
- Errors in async code:
setTimeoutcallbacks and promise rejections. - Errors during server-side rendering.
- Errors thrown in the error boundary itself.
Catch those with try/catch and put the error into state, which makes the next render show the error UI.
233. How do you handle errors from async operations?
async function handleSave() {
setStatus('saving');
try {
await saveDraft(draft);
setStatus('saved');
} catch (err) {
setStatus('error');
setError(err instanceof Error ? err.message : 'Something went wrong');
}
}
Also check response.ok, since fetch only rejects on network failures, not on 4xx or 5xx responses. That detail catches a lot of candidates.
234. What UI states should a data-driven component handle?
Four, at least: loading (a skeleton that matches the final layout), error (a message and a retry action), empty (a helpful message, not a blank area), and success. Add partial or stale states for refetching in the background. Interviewers notice when you handle empty and error states without being asked.
235. How do you implement infinite scroll in React?
Place a sentinel element after the last item and watch it with an IntersectionObserver. When it becomes visible, fetch the next page (cursor-based pagination is safer than page numbers for changing feeds) and append the results.
useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting && hasMore && !isLoading) loadMore();
}, { rootMargin: '400px' });
if (sentinelRef.current) observer.observe(sentinelRef.current);
return () => observer.disconnect();
}, [hasMore, isLoading, loadMore]);
For long feeds, combine it with virtualization, and offer a “Load more” button as an accessible fallback. Practice: Infinite Scrolling News Feed and HN Hiring Feed.
236. Polling vs WebSockets vs server-sent events: how do you choose?
| Option | Direction | Good for |
|---|---|---|
| Polling | Client asks repeatedly | Infrequent updates, simple infrastructure |
| Server-sent events | Server to client | Notifications, live scores, streaming LLM output |
| WebSockets | Both ways | Chat, collaboration, multiplayer |
See Web Protocols Cheat Sheet and How to Stream LLM Responses in the Browser.
237. How do you show a not-found page for unknown routes?
Add a catch-all route (path: '*' in React Router, not-found.tsx in Next.js). For server-rendered apps, also return a real 404 status code so search engines don’t index the error page. For valid routes with missing data (a deleted user), render the not-found UI from the route’s loader or component.
238. How do you retry failed requests?
Retry only errors that might succeed next time (network errors, 5xx, 429), not 4xx validation errors. Use exponential backoff with jitter so many clients don’t retry at the same moment, and cap the attempts.
async function fetchWithRetry(url, retries = 3) {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url);
if (res.status < 500 && res.status !== 429) return res;
throw new Error(`HTTP ${res.status}`);
} catch (err) {
if (attempt >= retries) throw err;
const delay = 2 ** attempt * 300 + Math.random() * 100;
await new Promise((r) => setTimeout(r, delay));
}
}
}
TanStack Query retries failed queries three times by default.
239. How do you prefetch data before the user navigates?
Start the request when intent is likely: on link hover or focus, when a link enters the viewport, or right after the current page settles. Store the result in your data cache (TanStack Query’s prefetchQuery, router loaders), so the next page renders instantly. Don’t prefetch everything; it wastes bandwidth on mobile and loads your API.
240. How would you cache API responses on the client?
Use a cache keyed by request (a data-fetching library does this), decide how long each kind of data stays fresh, and invalidate after mutations. Layer in HTTP caching (Cache-Control, ETags) so the browser can skip or shorten requests. For offline support, a service worker can serve cached responses. Deep dives: Apollo Cache and Normalization.
React 18, React 19, and Server Components

Find in-depth explanations and practice here: SSR vs CSR ->
Interviewers at companies on recent React versions ask these to check that your knowledge is current. You don’t need every API memorized, but you should know what problem each one solves.
241. What did React 18 introduce?
- Concurrent rendering, the foundation for everything below.
- Automatic batching of state updates everywhere, not just in event handlers.
- Transitions (
startTransition,useTransition,useDeferredValue) to mark updates as non-urgent. - Streaming SSR with Suspense and selective hydration.
- New root API (
createRoot,hydrateRoot), plususeIdanduseSyncExternalStore.
242. What is concurrent rendering?
Concurrent rendering lets React prepare several versions of the UI at once and interrupt a render in progress. A long, non-urgent render (filtering 10,000 rows) can pause so React handles an urgent one (a keystroke) first, then resume or restart.
It’s opt-in per update: only updates marked as transitions, or deferred values, are interruptible. Regular updates still render synchronously.
243. What’s new in React 19?
| Feature | What it solves |
|---|---|
| Actions, useActionState, useFormStatus | Pending, error, and result state for async mutations |
| useOptimistic | Instant UI while a mutation runs |
| use | Read promises and context during render, even conditionally |
| ref as a prop | No more forwardRef |
| Context as a provider | <MyContext value> instead of .Provider |
| Document metadata | <title> and <meta> rendered from any component |
| Server Components and Server Functions | Stable for frameworks to build on |
React 19.2 later added <Activity> and a stable useEffectEvent.
244. What are Actions in React 19?
An Action is an async function used in a transition. React tracks it for you: it sets pending state while it runs, handles errors through error boundaries, supports optimistic updates, and with forms, resets the form on success.
const [isPending, startTransition] = useTransition();
function handleSave() {
startTransition(async () => {
const error = await updateName(name);
if (error) setError(error);
});
}
Passing a function to <form action> or <button formAction> makes it an Action automatically.
245. What does useActionState do?
It wraps an Action and returns its latest result plus a pending flag. The action receives the previous state and the form data.
async function addToCart(prevState, formData) {
const result = await api.add(formData.get('itemId'));
return result.ok ? { message: 'Added!' } : { message: result.error };
}
function AddButton({ itemId }) {
const [state, formAction, isPending] = useActionState(addToCart, { message: '' });
return (
<form action={formAction}>
<input type="hidden" name="itemId" value={itemId} />
<button disabled={isPending}>Add to cart</button>
<p aria-live="polite">{state.message}</p>
</form>
);
}
246. What does useFormStatus do?
useFormStatus() (from react-dom) returns the status of the parent <form>: pending, data, method, and action. It lets a reusable submit button know the form is submitting without prop drilling. It must be called from a component rendered inside the form, not in the component that renders the form.
247. What does the use API do?
use(resource) reads a promise or a context during render. With a promise, the component suspends until it resolves (showing the nearest Suspense fallback) and throws to the nearest error boundary if it rejects.
function Comments({ commentsPromise }) {
const comments = use(commentsPromise); // suspends until resolved
return comments.map((c) => <p key={c.id}>{c.text}</p>);
}
Unlike hooks, use can be called inside conditions and loops. Don’t create the promise inside the same client component during render, or it’s recreated every render; create it in a Server Component, a loader, or a cache.
248. What does useOptimistic do?
It shows a temporary state while an Action is in progress, and automatically switches back to the real state when the Action finishes or fails.
function LikeButton({ likes, onLike }) {
const [optimisticLikes, addOptimistic] = useOptimistic(likes, (current, delta) => current + delta);
async function action() {
addOptimistic(1);
await onLike(); // when this settles, the real likes value takes over
}
return <form action={action}><button>♥ {optimisticLikes}</button></form>;
}
249. How do you set the page title and meta tags in React 19?
Render <title>, <meta>, and <link> anywhere in your components. React hoists them into the document <head>, on the client and in server rendering. That replaces libraries like react-helmet for simple cases. Frameworks still offer their own metadata APIs (Next.js’s metadata export) with more features, such as merging across layouts.
250. What are React Server Components?
Server Components are components that run only on the server (at build time or per request). They can be async, read databases or files directly, and their code is never sent to the browser. Only their rendered output is sent, in a serialized format that React merges into the client tree.
// Server Component: no 'use client', can be async
export default async function ProductPage({ params }) {
const product = await db.products.find(params.id);
return (
<>
<h1>{product.name}</h1>
<AddToCartButton id={product.id} /> {/* a Client Component */}
</>
);
}
Benefits: less JavaScript in the browser, no client-server waterfalls for data, and secrets stay on the server.
251. Server Components vs Client Components: how do you choose?
| Need | Server Component | Client Component |
|---|---|---|
| Fetch data, access backend | Yes | Through an API |
| Keep secrets and large dependencies off the client | Yes | No |
| State, effects, event handlers | No | Yes |
| Browser APIs | No | Yes |
Default to Server Components and add 'use client' at the leaves that need interactivity: the button, not the whole page.
252. What does ‘use client’ actually mean?
It marks a module as the boundary where code starts running on the client. That file and everything it imports become part of the client bundle. It doesn’t mean “render only in the browser”: Client Components are still server-rendered to HTML for the first load, then hydrated.
A Server Component can render a Client Component. A Client Component can’t import a Server Component, but it can receive one as children or another prop, which is how you nest server content inside client wrappers.
253. What are Server Functions (‘use server’)?
Functions marked with 'use server' run on the server but can be called from the client, like a typed RPC. The framework creates an endpoint for each one. They’re typically used as form actions for mutations.
The security point that interviewers want: a Server Function is a public HTTP endpoint. Validate the input and check authentication and authorization inside every one, exactly like an API route. Never trust that it can only be called from your UI.
254. What’s the difference between Server Components and SSR?
SSR renders your component tree (including Client Components) to HTML for the first page load, then the full JavaScript for those components loads and hydrates. Server Components are components whose code never goes to the client at all, on first load or on later navigations.
They’re complementary: frameworks use SSR to produce HTML from both server and client components. RSC reduces how much JavaScript needs to hydrate.
255. How does streaming SSR work?
Instead of waiting for the whole page to render on the server, React sends HTML in chunks. Parts wrapped in Suspense that are still loading are sent as fallbacks first; when their data is ready, React streams the real HTML with a small inline script that swaps it into place.
The user sees the page shell and fast content immediately, and slow sections fill in, rather than staring at a blank screen until the slowest query finishes.
256. What is selective hydration?
With streaming and Suspense, React hydrates the page in pieces instead of all at once. Each Suspense boundary hydrates independently, and if the user clicks an area that isn’t hydrated yet, React prioritizes hydrating that part first. The result is a page that becomes interactive sooner, especially on slow devices.
257. What is the Activity component?
<Activity mode="visible" | "hidden"> (React 19.2) hides part of the UI while keeping its state and DOM, instead of unmounting it. Hidden content has its effects cleaned up and renders at low priority in the background.
Use cases: keeping a tab’s state (scroll position, form input) when switching tabs, and pre-rendering a screen the user is likely to open next.
258. What are React DOM’s resource preloading APIs?
React 19 adds functions such as preload, preinit, preconnect, and prefetchDNS from react-dom. They tell the browser to start loading fonts, stylesheets, scripts, or connections early, and React deduplicates them and places the right tags in the document head.
import { preload, preconnect } from 'react-dom';
function Hero() {
preconnect('https://cdn.example.com');
preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' });
return <h1>Welcome</h1>;
}
259. What breaking changes did React 19 make?
- Removed
ReactDOM.renderandhydrate(usecreateRootandhydrateRoot). - Removed
propTypeschecks anddefaultPropsfor function components. - Removed legacy context (
contextTypes) and string refs. - Errors thrown during render are no longer re-thrown; they go to
window.reportErroror the root’sonUncaughtError/onCaughtErroroptions. - Requires the new JSX transform.
The React team published codemods for most of these, and React 18.3 added warnings for each deprecated API to help with the migration.
260. What does cache do in Server Components?
cache(fn) memoizes a function’s result for the duration of one server request. If several Server Components call getUser(id) while rendering the same page, the database is queried once.
import { cache } from 'react';
export const getUser = cache(async (id) => {
return db.users.find(id);
});
It’s per request, so different users never share results. It’s different from a framework’s data cache, which can persist across requests.
Testing and Accessibility in React

Find in-depth explanations and practice here: Accessibility Interview Questions ->
Senior candidates are expected to bring these up on their own. Mentioning how you’d test a component, or how a keyboard user would use it, is an easy way to stand out in a UI round.
261. How do you test React components?
Test what the user sees and does, not implementation details. Render the component, interact with it the way a user would (click, type), and assert on the visible result.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('adds a todo', async () => {
const user = userEvent.setup();
render(<TodoApp />);
await user.type(screen.getByRole('textbox', { name: /new todo/i }), 'Buy milk');
await user.click(screen.getByRole('button', { name: /add/i }));
expect(screen.getByRole('listitem')).toHaveTextContent('Buy milk');
});
The standard stack: Vitest or Jest as the runner, React Testing Library for components, and Playwright for end-to-end tests.
262. What is the philosophy of React Testing Library?
“The more your tests resemble the way your software is used, the more confidence they can give you.” In practice:
- Query by role and accessible name first (
getByRole('button', { name: 'Save' })), then label text, then text. Usedata-testidas a last resort. - Don’t test state values, hook calls, or component internals. A refactor that doesn’t change behavior shouldn’t break tests.
A nice side effect: if you can’t find an element by role, it’s probably not accessible.
263. getBy vs queryBy vs findBy: when do you use each?
| Query | If not found | Use for |
|---|---|---|
| getBy | Throws | Elements that should be there now |
| queryBy | Returns null | Asserting something is absent |
| findBy | Rejects after a timeout | Elements that appear asynchronously |
Each has an All variant (getAllByRole) that returns an array.
264. user-event vs fireEvent?
fireEvent dispatches a single DOM event. user-event simulates a full interaction the way a browser would: typing fires keydown, keypress, input, and keyup for each character, and clicking fires pointer and mouse events and moves focus. Prefer user-event; it catches bugs that a single synthetic event misses.
265. How do you test asynchronous behavior?
Use findBy* queries, which wait for an element to appear, or waitFor for other assertions.
render(<UserProfile id="1" />);
expect(screen.getByText(/loading/i)).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Ada Lovelace' })).toBeInTheDocument();
Avoid arbitrary sleeps (setTimeout in tests). For timers, use fake timers (vi.useFakeTimers()) and advance them explicitly.
266. How do you mock API calls in component tests?
Mock at the network level with Mock Service Worker (MSW), which intercepts fetch requests and returns fixture responses. Your components, hooks, and data library run unchanged, so tests exercise real code paths. The same handlers can power local development and Storybook. Mocking your own fetch wrapper module also works, but it skips more real code.
267. How do you test a custom hook?
Prefer testing it through a component that uses it. For reusable hooks, use renderHook:
import { renderHook, act } from '@testing-library/react';
test('useCounter increments', () => {
const { result } = renderHook(() => useCounter(5));
act(() => result.current.increment());
expect(result.current.count).toBe(6);
});
268. Are snapshot tests a good idea?
Rarely for components. Large snapshots break on every markup change, people approve updates without reading them, and they don’t say what behavior matters. They’re useful for small, stable outputs: a serialized config, an error message, or a utility’s output. For UI, prefer explicit assertions or visual regression tests.
269. Unit vs integration vs end-to-end tests: what’s the balance?
Unit tests check pure logic (reducers, utilities, hooks) and are fast. Integration tests render a feature with its children and mocked network, and give the most confidence per minute spent in React apps. End-to-end tests run the real app in a browser (Playwright) and cover a few critical flows such as sign-up and checkout. Background: Functional and integration tests.
270. What is act(), and why do I see act() warnings?
act() makes sure all state updates, effects, and re-renders triggered by an action finish before you assert. React Testing Library wraps render, user-event, and findBy/waitFor in act for you. A warning usually means something updated after your test moved on (an unawaited promise or timer), so the test should await the resulting UI with findBy.
271. How do you make a React app accessible?
- Use semantic HTML first:
<button>,<a href>,<label>, headings, landmarks. ARIA is for gaps, not a replacement. - Make everything work with the keyboard and keep focus visible.
- Label every input and give images meaningful
alttext (emptyalt=""for decorative ones). - Manage focus when content changes (dialogs, route changes, errors).
- Announce dynamic updates with live regions.
- Meet color contrast requirements and respect
prefers-reduced-motion.
Deep dives: Web Accessibility and ARIA roles.
272. What does an accessible modal need?
role="dialog"witharia-modal="true"and a label (aria-labelledbypointing to its title).- Focus moves into the dialog on open and is trapped there while it’s open.
- Escape closes it, and focus returns to the element that opened it.
- Content behind it is inert (the
inertattribute) so screen readers and Tab can’t reach it.
The native <dialog> element with showModal() gives you most of this for free. Practice: Focus-Trapped Dialog and Design an Accessible Dialog.
273. How do you announce dynamic changes to screen reader users?
Use a live region: an element with aria-live="polite" (or role="status") that exists on the page before the change. When its text content changes, screen readers announce it without moving focus. Use aria-live="assertive" (or role="alert") only for urgent messages like errors.
<p role="status">{results.length} results found</p>
The common mistake is rendering the live region at the same moment as its content; many screen readers miss it.
274. What accessibility problems do client-side route changes cause?
With a full page load, screen readers announce the new page title and focus resets to the top. With client-side navigation, nothing happens by default: focus stays on the clicked link, which may no longer exist. Fix it by moving focus to the new page’s main heading (or a skip target) and updating document.title. Some frameworks include a route announcer.
275. How do you test accessibility?
Combine automated and manual checks. Automated tools (axe via jest-axe, the Playwright axe integration, or Lighthouse) catch the mechanical issues: missing labels, low contrast, invalid ARIA. They can’t tell whether focus order makes sense or an announcement is useful, so key flows need manual testing: use the page with only a keyboard, then with a screen reader (VoiceOver, NVDA) for key flows. Querying by role in your tests also enforces accessible markup continuously.
React Coding Interview Questions

Find in-depth explanations and solve these in the browser with tests: React coding questions ->
In a UI coding round you have 45-60 minutes to build a working component. Interviewers grade four things: a sensible state model, working code, edge cases, and accessibility. Each question below gives the key idea and a compact solution. The linked problems have full requirements, tests, and reference solutions.
A process that works for every one of them: clarify requirements, decide the minimal state, build the happy path, then handle edge cases (empty, rapid clicks, keyboard), and talk through what you’d test.
276. Build an accordion.
Key idea: store which sections are open as a Set of ids, support “one at a time” and “many at a time”, and use a real <button> with aria-expanded for each header.
function Accordion({ sections, allowMultiple = false }) {
const [openIds, setOpenIds] = useState(() => new Set());
function toggle(id) {
setOpenIds((prev) => {
const next = new Set(allowMultiple ? prev : []);
if (prev.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
return sections.map(({ id, title, content }) => {
const isOpen = openIds.has(id);
return (
<div key={id}>
<h3>
<button id={`header-${id}`} aria-expanded={isOpen} aria-controls={`panel-${id}`} onClick={() => toggle(id)}>
{title}
</button>
</h3>
<div id={`panel-${id}`} role="region" aria-labelledby={`header-${id}`} hidden={!isOpen}>
{content}
</div>
</div>
);
});
}
Practice: Accordion, then Accessible FAQ Accordion.
277. Build a tabs component with keyboard support.
Key idea: only the active tab is in the tab order (tabIndex 0, the rest -1, called a roving tabindex), and arrow keys move between tabs.
function Tabs({ tabs }) {
const [active, setActive] = useState(0);
const tabRefs = useRef([]);
function onKeyDown(e) {
const delta = { ArrowRight: 1, ArrowLeft: -1 }[e.key];
if (!delta) return;
const next = (active + delta + tabs.length) % tabs.length;
setActive(next);
tabRefs.current[next].focus();
}
const current = tabs[active];
return (
<>
<div role="tablist" onKeyDown={onKeyDown}>
{tabs.map((tab, i) => (
<button
key={tab.id}
ref={(el) => { tabRefs.current[i] = el; }}
role="tab"
id={`tab-${tab.id}`}
aria-selected={i === active}
aria-controls={`panel-${tab.id}`}
tabIndex={i === active ? 0 : -1}
onClick={() => setActive(i)}
>
{tab.label}
</button>
))}
</div>
<div role="tabpanel" id={`panel-${current.id}`} aria-labelledby={`tab-${current.id}`}>
{current.content}
</div>
</>
);
}
Follow-ups: Home and End keys, vertical tabs with up and down arrows, and lazy-rendering panels. Practice: Tabs and Accessible Tabs.
278. Build a star rating component.
Key idea: the displayed rating is the hovered star if any, otherwise the selected value. Model it as a radio group so it’s accessible.
function StarRating({ max = 5, value, onChange }) {
const [hovered, setHovered] = useState(0);
const shown = hovered || value;
return (
<div role="radiogroup" aria-label="Rating" onMouseLeave={() => setHovered(0)}>
{Array.from({ length: max }, (_, i) => i + 1).map((star) => (
<button
key={star}
role="radio"
aria-checked={value === star}
aria-label={`${star} star${star > 1 ? 's' : ''}`}
onMouseEnter={() => setHovered(star)}
onClick={() => onChange(star)}
>
{star <= shown ? '★' : '☆'}
</button>
))}
</div>
);
}
Practice: Star Rating System.
279. Build progress bars that fill one after another, with a concurrency limit.
Key idea: each bar is either queued, filling, or done. Derive which bars are active (the first N not done) instead of storing it, and let CSS do the animation.
function ProgressBar({ isActive, onDone }) {
const [filled, setFilled] = useState(false);
useEffect(() => {
if (!isActive) return;
const id = requestAnimationFrame(() => setFilled(true)); // let 0% paint first
return () => cancelAnimationFrame(id);
}, [isActive]);
return (
<div className="track">
<div
className="fill"
style={{ width: filled ? '100%' : '0%', transition: 'width 2s linear' }}
onTransitionEnd={onDone}
/>
</div>
);
}
function ProgressQueue({ limit = 3 }) {
const [bars, setBars] = useState([]);
const add = () => setBars((b) => [...b, { id: crypto.randomUUID(), done: false }]);
const finish = (id) => setBars((b) => b.map((bar) => (bar.id === id ? { ...bar, done: true } : bar)));
const activeIds = new Set(bars.filter((b) => !b.done).slice(0, limit).map((b) => b.id));
return (
<>
<button onClick={add}>Add</button>
{bars.map((bar) => (
<ProgressBar key={bar.id} isActive={activeIds.has(bar.id) || bar.done} onDone={() => finish(bar.id)} />
))}
</>
);
}
Practice: Progress Bar and Pausable Export Queue.
280. Build an image carousel with autoplay.
Key idea: one index state with wrap-around math, an interval that pauses on hover and focus, and a cleanup so changing slides manually doesn’t stack intervals.
function Carousel({ images, interval = 4000 }) {
const [index, setIndex] = useState(0);
const [paused, setPaused] = useState(false);
const count = images.length;
const go = (delta) => setIndex((i) => (i + delta + count) % count);
useEffect(() => {
if (paused || count < 2) return;
const id = setInterval(() => setIndex((i) => (i + 1) % count), interval);
return () => clearInterval(id);
}, [paused, interval, count]);
return (
<section aria-roledescription="carousel" onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}
onFocus={() => setPaused(true)} onBlur={() => setPaused(false)}>
<img src={images[index].src} alt={images[index].alt} />
<button aria-label="Previous slide" onClick={() => go(-1)}>‹</button>
<button aria-label="Next slide" onClick={() => go(1)}>›</button>
<p aria-live={paused ? 'polite' : 'off'}>Slide {index + 1} of {count}</p>
</section>
);
}
Follow-ups: preloading the next image, swipe gestures, and respecting prefers-reduced-motion. Practice: Image Slider and Lean Photo Carousel.
281. Build tic-tac-toe.
Key idea: store only the board. Derive the next player, the winner, and the draw state from it, so they can never get out of sync.
const LINES = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
];
function getWinner(board) {
for (const [a, b, c] of LINES) {
if (board[a] && board[a] === board[b] && board[a] === board[c]) return board[a];
}
return null;
}
console.log(getWinner(['X', 'X', 'X', null, 'O', 'O', null, null, null])); // "X"
function TicTacToe() {
const [board, setBoard] = useState(Array(9).fill(null));
const winner = getWinner(board);
const xIsNext = board.filter(Boolean).length % 2 === 0;
const isDraw = !winner && board.every(Boolean);
function play(i) {
if (board[i] || winner) return;
setBoard(board.with(i, xIsNext ? 'X' : 'O'));
}
// render 9 buttons with aria-label={`Cell ${i + 1}, ${board[i] ?? 'empty'}`}
}
Follow-ups: an N x N board with K in a row, undo with a history array, and a computer opponent. Practice: Tic Tac Toe, then K-in-a-Row Game and Connect Four.
282. Build an autocomplete (typeahead) search.
Key idea: debounce the query, cancel stale requests so old results never overwrite new ones, cache results by query, and implement the ARIA combobox pattern for keyboard users.
function Autocomplete({ fetchSuggestions }) {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [active, setActive] = useState(-1);
const debounced = useDebouncedValue(query, 250);
useEffect(() => {
if (!debounced.trim()) { setResults([]); return; }
const controller = new AbortController();
fetchSuggestions(debounced, controller.signal)
.then((items) => { setResults(items); setActive(-1); })
.catch((err) => { if (err.name !== 'AbortError') setResults([]); });
return () => controller.abort();
}, [debounced, fetchSuggestions]);
function onKeyDown(e) {
if (e.key === 'ArrowDown') setActive((i) => Math.min(i + 1, results.length - 1));
if (e.key === 'ArrowUp') setActive((i) => Math.max(i - 1, 0));
if (e.key === 'Enter' && active >= 0) setQuery(results[active].label);
if (e.key === 'Escape') setResults([]);
}
return (
<div>
<input role="combobox" aria-expanded={results.length > 0} aria-controls="suggestions"
aria-activedescendant={active >= 0 ? `option-${results[active].id}` : undefined}
value={query} onChange={(e) => setQuery(e.target.value)} onKeyDown={onKeyDown} />
<ul id="suggestions" role="listbox">
{results.map((r, i) => (
<li key={r.id} id={`option-${r.id}`} role="option" aria-selected={i === active}>{r.label}</li>
))}
</ul>
</div>
);
}
This is one of the most common frontend questions, as a coding round and as system design. Practice: Autocomplete Search List and API Search and Render Image. Design version: Design Auto Complete Search.
283. Build a to-do list.
Key idea: a reducer with add, toggle, edit, and delete actions; ids generated when an item is created; and the filtered view (all, active, completed) derived during render.
function todosReducer(todos, action) {
switch (action.type) {
case 'add':
return [...todos, { id: action.id, text: action.text, done: false }];
case 'toggle':
return todos.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
case 'edit':
return todos.map((t) => (t.id === action.id ? { ...t, text: action.text } : t));
case 'delete':
return todos.filter((t) => t.id !== action.id);
default:
return todos;
}
}
let todos = todosReducer([], { type: 'add', id: 'a', text: 'Ship it' });
todos = todosReducer(todos, { type: 'toggle', id: 'a' });
console.log(todos[0].done); // true
Edge cases interviewers check: trimming and rejecting empty input, Enter to submit, and the remaining count. Practice: To-do App.
284. Build nested comments with replies.
Key idea: a recursive component. The harder part is the data: adding a reply to a deeply nested tree needs a recursive immutable update, so many solutions normalize comments into a map of id to comment with childIds.
function Comment({ id, commentsById, onReply }) {
const comment = commentsById[id];
const [isReplying, setIsReplying] = useState(false);
return (
<li>
<p>{comment.text}</p>
<button onClick={() => setIsReplying(true)}>Reply</button>
{isReplying && (
<ReplyForm onSubmit={(text) => { onReply(id, text); setIsReplying(false); }} />
)}
{comment.childIds.length > 0 && (
<ul>
{comment.childIds.map((childId) => (
<Comment key={childId} id={childId} commentsById={commentsById} onReply={onReply} />
))}
</ul>
)}
</li>
);
}
With the normalized shape, adding a reply touches two entries: the new comment and its parent’s childIds. Practice: Nested Comments I and Nested Comments II.
285. Build a file explorer tree.
Key idea: render the tree recursively, keep expanded folder ids in a Set at the top, sort folders before files, and follow the ARIA tree pattern (role="tree", treeitem, aria-expanded, arrow-key navigation) for the accessible version.
function TreeNode({ node, expanded, onToggle, depth = 0 }) {
const isFolder = Boolean(node.children);
const isOpen = expanded.has(node.id);
return (
<li role="treeitem" aria-expanded={isFolder ? isOpen : undefined}>
<button style={{ paddingLeft: depth * 16 }} onClick={() => isFolder && onToggle(node.id)}>
{isFolder ? (isOpen ? '📂' : '📁') : '📄'} {node.name}
</button>
{isFolder && isOpen && (
<ul role="group">
{[...node.children]
.sort((a, b) => Number(Boolean(b.children)) - Number(Boolean(a.children)) || a.name.localeCompare(b.name))
.map((child) => (
<TreeNode key={child.id} node={child} expanded={expanded} onToggle={onToggle} depth={depth + 1} />
))}
</ul>
)}
</li>
);
}
Practice: File Navigation and Accessible File Tree.
286. Build a nested checkbox tree with indeterminate parents.
Key idea: store only the checked leaf ids. A parent’s state (checked, unchecked, or indeterminate) is derived from its children, and toggling a parent checks or unchecks all its leaves. indeterminate can only be set through a DOM property, so it needs a ref.
function getCheckState(node, checked) {
if (!node.children?.length) return checked.has(node.id) ? 'checked' : 'unchecked';
const states = node.children.map((child) => getCheckState(child, checked));
if (states.every((s) => s === 'checked')) return 'checked';
if (states.every((s) => s === 'unchecked')) return 'unchecked';
return 'indeterminate';
}
const tree = { id: 'all', children: [{ id: 'a' }, { id: 'b' }] };
console.log(getCheckState(tree, new Set(['a']))); // "indeterminate"
console.log(getCheckState(tree, new Set(['a', 'b']))); // "checked"
function TriStateCheckbox({ state, onChange, label }) {
const ref = useRef(null);
useEffect(() => {
ref.current.indeterminate = state === 'indeterminate';
}, [state]);
return (
<label>
<input ref={ref} type="checkbox" checked={state === 'checked'} onChange={onChange} /> {label}
</label>
);
}
Practice: Hierarchical Checkbox.
287. Build a sortable, paginated data table.
Key idea: store only the raw rows, the sort config, and the page. Sorted rows and the current page are derived. Reset to page 1 when the sort changes, and expose the sort with aria-sort on the header.
function DataTable({ rows, columns, pageSize = 10 }) {
const [sort, setSort] = useState({ key: columns[0].key, dir: 'asc' });
const [page, setPage] = useState(0);
const sorted = useMemo(() => {
const factor = sort.dir === 'asc' ? 1 : -1;
return rows.toSorted((a, b) => (a[sort.key] > b[sort.key] ? 1 : a[sort.key] < b[sort.key] ? -1 : 0) * factor);
}, [rows, sort]);
const pageCount = Math.max(1, Math.ceil(sorted.length / pageSize));
const visible = sorted.slice(page * pageSize, (page + 1) * pageSize);
function sortBy(key) {
setSort((s) => ({ key, dir: s.key === key && s.dir === 'asc' ? 'desc' : 'asc' }));
setPage(0);
}
// header: <th aria-sort={sort.key === col.key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}>
// <button onClick={() => sortBy(col.key)}>{col.label}</button></th>
// footer: Prev / Next buttons disabled at 0 and pageCount - 1
}
Follow-ups: multi-column sort, server-side sorting and pagination for large data, and virtualization. Practice: Paginated Orders Table, Multi-Sort Data Table, and Inventory Data Grid.
288. Build a stopwatch.
Key idea: don’t count ticks. Intervals drift and pause in background tabs. Store when the current run started plus the time accumulated before it, and compute the elapsed time from the clock.
function Stopwatch() {
const [accumulated, setAccumulated] = useState(0);
const [startedAt, setStartedAt] = useState(null);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (startedAt === null) return;
const id = setInterval(() => setNow(Date.now()), 50);
return () => clearInterval(id);
}, [startedAt]);
const elapsed = accumulated + (startedAt === null ? 0 : now - startedAt);
const start = () => { const t = Date.now(); setStartedAt(t); setNow(t); };
const stop = () => { setAccumulated(elapsed); setStartedAt(null); };
const reset = () => { setAccumulated(0); setStartedAt(null); };
return (
<>
<p>{(elapsed / 1000).toFixed(2)}s</p>
{startedAt === null ? <button onClick={start}>Start</button> : <button onClick={stop}>Stop</button>}
<button onClick={reset}>Reset</button>
</>
);
}
Practice: Lap Split Stopwatch.
289. Build a traffic light.
Key idea: a small state machine in a config object (each state’s duration and next state) and one setTimeout per state, re-scheduled when the state changes. The config makes adding a state or changing timings a one-line change.
const LIGHTS = {
green: { next: 'yellow', ms: 3000 },
yellow: { next: 'red', ms: 1000 },
red: { next: 'green', ms: 4000 },
};
function TrafficLight() {
const [color, setColor] = useState('green');
useEffect(() => {
const id = setTimeout(() => setColor(LIGHTS[color].next), LIGHTS[color].ms);
return () => clearTimeout(id);
}, [color]);
return (
<div aria-label={`Light is ${color}`} role="img">
{Object.keys(LIGHTS).map((c) => <span key={c} className={`bulb ${c} ${c === color ? 'on' : ''}`} />)}
</div>
);
}
Practice: Crosswalk Traffic Signal.
290. Build a “type the name to confirm” delete dialog.
Key idea: use the native <dialog> with showModal() (focus trapping, Escape, and the backdrop come free), keep the destructive button disabled until the input matches, and return focus to the trigger on close.
function DeleteRepoDialog({ repoName, onConfirm, onClose }) {
const dialogRef = useRef(null);
const [typed, setTyped] = useState('');
useEffect(() => {
if (!dialogRef.current.open) dialogRef.current.showModal();
}, []);
return (
<dialog ref={dialogRef} onClose={onClose} aria-labelledby="delete-title">
<h2 id="delete-title">Delete {repoName}?</h2>
<label>
Type <strong>{repoName}</strong> to confirm
<input value={typed} onChange={(e) => setTyped(e.target.value)} autoFocus />
</label>
<button onClick={() => dialogRef.current.close()}>Cancel</button>
<button disabled={typed !== repoName} onClick={onConfirm}>Delete this repository</button>
</dialog>
);
}
Practice: Delete Repository Dialog and Unsaved Changes Modal.
291. Build a transfer list.
Key idea: two arrays plus a Set of selected items. Moving is a pure function, which makes it easy to test.
function transfer(from, to, selected) {
return [
from.filter((item) => !selected.has(item)),
[...to, ...from.filter((item) => selected.has(item))],
];
}
const [left, right] = transfer(['A', 'B', 'C'], ['D'], new Set(['B']));
console.log(left, right); // ["A", "C"] ["D", "B"]
In the component, clear moved items from the selection and disable the move buttons when nothing selected is on that side. Practice: Lineup Transfer List.
292. Build a memory (flip pairs) game.
Key idea: state is the shuffled deck, up to two flipped indexes, and a set of matched values. Lock input while two unmatched cards are showing, and flip them back after a timeout that you clear on unmount. Shuffle with Fisher-Yates:
function shuffle(items) {
const a = [...items];
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
console.log(shuffle([1, 1, 2, 2, 3, 3]).length); // 6
Mention that array.sort(() => Math.random() - 0.5) is a biased shuffle; interviewers notice. Practice: Flip Pairs Game.
293. Build a Wordle-style word guess grid.
Key idea: the UI is a grid of guesses, but the trap is scoring repeated letters. Mark exact matches first, then count the remaining answer letters before marking “present”.
function score(guess, answer) {
const result = Array(guess.length).fill('absent');
const remaining = {};
for (let i = 0; i < answer.length; i++) {
if (guess[i] === answer[i]) result[i] = 'correct';
else remaining[answer[i]] = (remaining[answer[i]] ?? 0) + 1;
}
for (let i = 0; i < guess.length; i++) {
if (result[i] !== 'correct' && remaining[guess[i]] > 0) {
result[i] = 'present';
remaining[guess[i]]--;
}
}
return result;
}
console.log(score('SPEED', 'ABIDE').join(' ')); // "absent absent present absent present"
Practice: Word Guess Grid.
294. Build a one-time code (OTP) input.
Key idea: an array of single-digit inputs with refs. Typing a digit moves focus forward, Backspace on an empty box moves back, and pasting fills every box at once.
function OtpInput({ length = 6, onComplete }) {
const [digits, setDigits] = useState(() => Array(length).fill(''));
const refs = useRef([]);
function update(next) {
setDigits(next);
if (next.every(Boolean)) onComplete(next.join(''));
}
function handleChange(i, value) {
const digit = value.replace(/\D/g, '').slice(-1);
update(digits.with(i, digit));
if (digit && i < length - 1) refs.current[i + 1].focus();
}
function handleKeyDown(i, e) {
if (e.key === 'Backspace' && !digits[i] && i > 0) refs.current[i - 1].focus();
}
function handlePaste(e) {
const pasted = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, length);
if (!pasted) return;
e.preventDefault();
update(Array.from({ length }, (_, i) => pasted[i] ?? ''));
refs.current[Math.min(pasted.length, length - 1)].focus();
}
return digits.map((d, i) => (
<input key={i} ref={(el) => { refs.current[i] = el; }} value={d} inputMode="numeric"
autoComplete={i === 0 ? 'one-time-code' : 'off'} aria-label={`Digit ${i + 1}`} maxLength={1}
onChange={(e) => handleChange(i, e.target.value)} onKeyDown={(e) => handleKeyDown(i, e)} onPaste={handlePaste} />
));
}
Using the index as a key is fine here: the list never reorders. Practice: Authentication Code.
295. Write a hook that loads async data with loading and error state.
Key idea: one state object with a status field (so loading and error can’t both be true), an ignore flag to drop stale responses, and a stable loader function from the caller.
function useAsyncResource(load) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
let ignore = false;
setState((s) => ({ ...s, status: 'loading', error: null }));
load().then(
(data) => { if (!ignore) setState({ status: 'success', data, error: null }); },
(error) => { if (!ignore) setState({ status: 'error', data: null, error }); }
);
return () => { ignore = true; };
}, [load]);
return state;
}
// Caller keeps the loader stable so the effect only re-runs when userId changes:
const loadUser = useCallback(() => api.getUser(userId), [userId]);
const { status, data, error } = useAsyncResource(loadUser);
Keeping the previous data while reloading avoids flashing an empty screen. Practice: useAsyncResource.
Senior React Interview Questions

Find in-depth explanations and practice here: Design A Scalable Frontend Architecture ->
These are the React interview questions for experienced developers. For senior and staff roles, interviewers move from “how does this API work” to “how would you run this at scale”. There are no single right answers here. They grade whether your decisions come with reasons and trade-offs.
| Junior answers | Senior answers |
|---|---|
| Name a library | Name the problem first, then the tool and why |
| Describe one approach | Compare two approaches and pick one for this context |
| Focus on code | Cover users, team, performance, and maintenance |
| “It depends” | “It depends on X; here, X is true, so I’d do Y” |
296. How would you structure a large React application?
- Organize by feature (checkout, search, profile), each with its components, hooks, data access, and tests, and a small public API (an index file) that other features import from.
- Separate layers: shared UI (design system), feature modules, a data layer (API clients, query hooks), and platform services (auth, analytics, feature flags, logging).
- Enforce boundaries with lint rules (no deep imports into another feature) so the structure survives as the team grows.
- Keep views thin: components render; hooks hold logic and talk to the data layer.
Deep dives: Layered Frontend Architecture and MVVM in Frontend Applications.
297. How would you design a reusable component library?
- Accessible by default: keyboard support, focus management, and ARIA built into every component, so product teams can’t get it wrong.
- Composable APIs: compound components and
childreninstead of dozens of configuration props. - Headless core plus styles: behavior in hooks or unstyled primitives, visuals from design tokens (CSS variables), so themes and brands are cheap.
- Escape hatches: forward
ref,className, and native props. - Process: Storybook docs, visual regression tests, semantic versioning, and codemods for breaking changes.
Related design questions: Design an Action Menu and Design a Theme Switcher.
298. When would you use micro frontends?
When many independent teams need to ship parts of one product on separate release schedules, and the organizational cost of coordinating one deploy is higher than the technical cost of splitting. Implementations range from build-time packages, to Module Federation, to separate apps per route.
The costs: duplicated dependencies and larger bundles, inconsistent UX, shared state and routing across apps, and harder local development. For most companies, a well-structured monorepo with clear ownership gives the team independence without those costs.
299. How do you choose a rendering strategy for a new product?
| Page type | Strategy | Why |
|---|---|---|
| Marketing, docs, blog | Static generation | Fast, cacheable, SEO |
| Product pages, search results | SSR or RSC with streaming | SEO plus fresh data |
| Logged-in dashboard | CSR or RSC with client islands | No SEO need, heavy interactivity |
| Editor, canvas tool | CSR | Almost all interaction, local state |
Most real products mix them per route, which is the main reason to use a framework.
300. How do you implement feature flags in a React app?
Evaluate flags once (on the server or at startup), provide them through context or a flags SDK, and read them with a hook (useFlag('new-checkout')). Evaluate on the server when possible, so users don’t see the old UI flash before switching. Keep flags short-lived, remove dead branches after rollout, and log flag exposure for experiments. Design version: Design a Feature Flag SDK.
301. How do you internationalize a React app?
Use a library (react-intl / FormatJS, i18next) with message catalogs per locale and ICU message syntax for plurals and variables. Format dates, numbers, and currencies with Intl APIs, never string concatenation. Load only the active locale’s messages, support right-to-left layouts with logical CSS properties (margin-inline-start), and design layouts that survive translations much longer than the English text. Set lang on the document.
302. How do you catch and monitor errors in production?
- Error boundaries around routes and independent widgets, with useful fallback UIs.
- An error monitoring service (Sentry or similar) that captures render errors, unhandled promise rejections, and failed requests, with source maps uploaded so stack traces are readable.
- Release tagging, so you can tie a spike in errors to a deploy and roll back.
- Real user monitoring for Core Web Vitals, segmented by page and device.
303. What security issues should a React developer think about?
- XSS:
dangerouslySetInnerHTML,javascript:URLs, and rendering model output as HTML. Sanitize, and add a Content Security Policy. - Token storage: prefer HttpOnly, Secure, SameSite cookies over
localStorage, which any XSS can read. - Server Functions and API routes: authenticate and authorize inside each one.
- Secrets: anything in client code or
NEXT_PUBLIC_variables is public. - Dependencies: audit and pin them; supply-chain attacks target popular packages.
Deep dives: Frontend Security and Securing AI Features on the Frontend.
304. How would you migrate a large codebase to a new React version or architecture?
Incrementally, never as a big-bang rewrite. Upgrade to the last minor version first and fix its deprecation warnings (React 18.3 warns about everything React 19 removes). Run the official codemods, turn on StrictMode in one area at a time, and migrate route by route (Pages Router to App Router can coexist). Track progress with a lint rule or a script that counts remaining legacy patterns, and keep shipping features during the migration.
305. How would you handle state in a real-time collaborative UI?
Separate local, unconfirmed changes from server-confirmed state. Apply local edits optimistically, send them as operations, and reconcile with the server’s order of events. For simple fields, last-write-wins with timestamps may be enough; for text and shared documents, use CRDTs (Yjs, Automerge) or operational transforms. Show presence (who’s editing), handle reconnects by replaying missed events, and keep rendering fast with fine-grained subscriptions. Design versions: Design a Collaborative Editor and Design Figma.
306. How do you keep a React app fast as it grows?
Treat performance as a budget, not a cleanup project. Set limits (JavaScript per route, LCP and INP targets), check bundle size in CI, and fail or flag pull requests that exceed it. Collect real user metrics with the web-vitals library, review the slowest pages regularly, and assign owners. Lazy-load by default for heavy features, and adopt the React Compiler to remove most manual memoization work.
307. Tell me about a difficult React bug you fixed.
This is half technical, half behavioral. Structure it: the symptom and its impact, how you narrowed it down (reproduction, profiling, bisecting), the root cause, the fix, and what you changed so it can’t happen again (a lint rule, a test, a shared hook).
“Users on slow connections sometimes saw another customer’s order details for a second. I reproduced it by throttling the network: switching orders quickly let an older request resolve last. The effect didn’t cancel stale requests. I added an AbortController in the cleanup, wrote a test that resolves requests out of order, and moved order fetching to our query library so it’s handled in one place.”
A real story with a measurable impact beats a hypothetical one. Build your story bank with Behavioral Interviews for Frontend Engineers.
308. When would you not use React?
For mostly static content (a marketing site or blog) where plain HTML, a static site generator, or a framework that ships zero JavaScript by default fits better. For tiny widgets embedded in other sites, where React’s size is a large share of the payload (Preact or vanilla JavaScript is lighter). And for performance-critical canvas or WebGL work, where React adds little over the underlying API. Being able to argue against your own favorite tool is a senior signal.
309. What do you look for when reviewing React code?
- State in the right place: no derived or duplicated state, colocated where possible.
- Effects that are really event handlers or derived values, and effects missing cleanup or dependencies.
- Stable, unique keys in lists.
- Accessibility: semantic elements, labels, keyboard support.
- Loading, empty, and error states handled.
- Component size and naming: can you understand it without scrolling?
- Tests that assert behavior, not implementation.
310. How do you make a React app work offline?
Register a service worker (Workbox makes this manageable) that caches the app shell and static assets, and choose a caching strategy per request type: cache-first for versioned assets, stale-while-revalidate for content, network-first for user data. Store user data and queued mutations in IndexedDB, replay them when the connection returns, and show clear offline and syncing states in the UI. Deep dive: Image Caching Strategies.
How to Use This List
Don’t read 310 questions front to back the night before. Pick the sections that match the role, answer each question out loud before reading the answer, and practice the coding questions in an editor with a timer.
| Level | Focus on | Then practice |
|---|---|---|
| Junior / new grad | Fundamentals, JSX and components, props and state, core hooks | Accordion, tabs, to-do list, star rating |
| Mid-level | Rendering and keys, useEffect, performance, forms | Autocomplete, data table, nested comments, custom hooks |
| Senior / staff | State management, React 19 and Server Components, testing and accessibility, senior questions | A full UI build under time, plus a frontend system design round |
Where to go next on FrontendLead
- React coding questions: build real components in the browser, with tests and video solutions.
- JavaScript coding questions: debounce, promises, polyfills, and the other questions that show up alongside React.
- Frontend System Design Handbook: the RADIO framework and worked designs for senior rounds.
- Trivia questions and Quiz Yourself: quick checks for concepts like closures, the event loop, and reconciliation.
- React interview questions handbook chapter and the full Frontend Interview Handbook.
- Study plans: a day-by-day schedule from two weeks to six months, or build your own with the study plan tool.
- Company-specific questions: what Meta, Google, Amazon, and others actually ask.
React interviews reward people who understand the render cycle, not people who memorized hook definitions. Learn the “why”, build the components yourself, and the “what” follows.
Related reading: Frontend frameworks compared: React vs Vue vs Angular vs Svelte · Frontend testing: unit, integration, and E2E with interview questions · React frontend developer: skills, stack, and career guide · 120+ TypeScript interview questions and answers
