React interview questions

20 React interview questions and answers

The React questions that come up in frontend and full-stack interviews, from props and state to hooks, effects, re-rendering and server components. Each has a short answer you can say out loud, a fuller explanation with code where it helps and the follow-ups interviewers like to ask.

20 questions with a 30-second answer, a deeper explanation and the follow-ups interviewers usually ask.

How to use these questions

React interviews usually move through three layers. The first is fundamentals: components, props versus state, keys and controlled inputs. The second is hooks and effects: howuseEffect dependencies work, when to memoise and what a stale closure is. The third is architecture and performance: where state should live, how to avoid needless re-renders, how to split code and how server components change data fetching.

What changes with experience is the depth of the follow-ups. A fresher is expected to explain what a key is for. Someone with two to five years is expected to say what breaks when you use the index as a key, and how you would find a slow render with the Profiler. Senior candidates are asked to compare approaches and defend a trade-off.

Each card shows a difficulty and an experience level. Start with the ones marked Often asked, then work down. Say each answer aloud, because a React concept you can only recognise when you read it tends to fall apart when an interviewer asks you to explain it.

React

Hooks, reconciliation, performance and state

Q1EasyFresherOften asked

What is the virtual DOM and how does reconciliation work?

30-second answer: The virtual DOM is a lightweight copy of the UI in memory. When state changes, React builds a new copy, compares it with the old one, and updates only the parts of the real DOM that changed.

The virtual DOM is a lightweight JavaScript representation of the UI. When state changes, React renders a new tree, diffs it against the previous one, and applies only the minimal set of real DOM changes.

The diff is O(n) because React assumes two things: elements of different types produce different trees, and key props identify stable children across renders.

Follow-up questions interviewers ask next

  • How does React Fiber change reconciliation?
  • Why is diffing O(n) and not O(n³)?
Q2EasyFresherOften asked

Why do list items need a stable key?

30-second answer: Keys tell React which item is which between renders, so it can move or reuse items instead of rebuilding them. Use a stable ID from your data, not the array index.

Keys let React match elements between renders. With a stable, unique key React can reorder, insert or remove items without destroying and recreating siblings, and component state stays attached to the right item.

Using the array index as a key breaks this whenever the list is reordered or filtered - inputs keep the wrong text, animations jump.

// Good: id comes from the data
{todos.map(t => <TodoItem key={t.id} todo={t} />)}

// Risky: index changes when the list is reordered
{todos.map((t, i) => <TodoItem key={i} todo={t} />)}

Follow-up questions interviewers ask next

  • What happens if two siblings share a key?
  • When is using the index as a key acceptable?
Q3EasyFresher

What is the difference between controlled and uncontrolled components?

30-second answer: Controlled: React state owns the input value through onChange. Uncontrolled: the DOM owns it and you read it with a ref. Pick controlled when you need validation or live formatting.

A controlled component keeps its value in React state and updates it through onChange; React is the single source of truth. An uncontrolled component lets the DOM hold the value and you read it through a ref when needed.

Use controlled inputs for validation, formatting or dependent fields. Uncontrolled inputs are fine for simple forms and file inputs.

const [name, setName] = useState("");
<input value={name} onChange={e => setName(e.target.value)} />

const ref = useRef(null);
<input defaultValue="Ada" ref={ref} />

Follow-up questions interviewers ask next

  • How do you keep large forms fast?
  • What is the difference between value and defaultValue?
Q4Medium2–5 years

useEffect vs useLayoutEffect - when would you choose each?

30-second answer: useEffect runs after paint, so it never blocks the screen. useLayoutEffect runs before paint - use it only when you must measure or fix layout to avoid a flicker.

useEffect runs after the browser has painted, so it never blocks rendering. useLayoutEffect runs synchronously after DOM mutations but before paint.

Default to useEffect. Reach for useLayoutEffect only when you must measure or mutate the DOM and re-render before the user sees a frame, e.g. positioning a tooltip from getBoundingClientRect() to avoid flicker.

Follow-up questions interviewers ask next

  • How does effect cleanup work?
  • What goes wrong with useLayoutEffect in server rendering?
Q5Medium2–5 yearsOften asked

useMemo vs useCallback - what do they actually save?

30-second answer: useMemo caches a computed value and useCallback caches a function. They only pay off for expensive work or when passing props to memoized children.

useMemo caches a computed value; useCallback caches a function identity. Both only re-compute when a dependency changes.

They matter when the value is expensive to compute or when it is passed to a memoized child (React.memo) or used as another hook's dependency. Wrapping everything by default adds cost and noise without benefit.

const sorted = useMemo(() => [...rows].sort(byDate), [rows]);
const onSelect = useCallback(id => setSelected(id), []);

Follow-up questions interviewers ask next

  • When does React.memo not help?
  • Is it OK to silence the exhaustive-deps warning?
Q6Medium2–5 years

What is a stale closure in a hook and how do you fix it?

30-second answer: A callback remembers the values from the render it was created in, so an effect with an empty dependency array keeps seeing old state. Fix it with correct dependencies, a functional update, or a ref.

A callback captures the values from the render in which it was created. If an effect or timer is created once with an empty dependency array, it keeps seeing the initial state forever.

Fix it by listing the dependency, using the functional form of the state setter, or storing the latest value in a ref.

// Bug: always logs 0
useEffect(() => {
  const id = setInterval(() => console.log(count), 1000);
  return () => clearInterval(id);
}, []);

// Fix: functional update needs no captured value
setCount(c => c + 1);

Follow-up questions interviewers ask next

  • How do refs help avoid stale closures?
  • What does the exhaustive-deps lint rule catch?
  • What is a closure, and how does it cause this?
Q7HardSenior

How does React batch state updates?

30-second answer: React collects state updates made in the same tick and re-renders once. Since React 18 this happens everywhere, not only in event handlers, and the state you read right after setState is still the old value.

React groups multiple setState calls made in the same tick into a single re-render. Since React 18 this is automatic everywhere - event handlers, promises, timeouts - not only inside React events.

Updates are queued and applied together, so reading state right after calling the setter still gives the old value. Use flushSync only when you truly need a synchronous DOM update.

Follow-up questions interviewers ask next

  • When would you reach for flushSync?
  • How do transitions change update priority?
Q8EasyFresher

What is the difference between props and state?

30-second answer: Props come from the parent and are read-only. State is owned by the component and changing it triggers a re-render. Do not store values in state that you can compute during render.

Props are inputs passed from a parent to a child; the child treats them as read-only. State is data a component owns and can change over time with a setter, and changing it triggers a re-render.

A useful rule: if a value can be computed from props or other state, do not store it in state. Derive it while rendering instead, which removes a whole class of out-of-sync bugs.

Follow-up questions interviewers ask next

  • Where should data that two sibling components need live?
  • Why is mutating state directly a bug?
Q9EasyFresher

What are the rules of hooks, and why do they exist?

30-second answer: Call hooks only at the top level of a component or custom hook, never in conditions or loops. React tracks hooks by call order, so the order must be the same on every render.

Hooks let function components use state and other React features. Two rules apply: call hooks only at the top level (never inside loops, conditions or nested functions), and call them only from React function components or custom hooks.

React identifies each hook by the order of the calls during a render. If a hook sits inside an if, the order can change between renders and every later hook reads the wrong state. The eslint-plugin-react-hooks rules catch these mistakes automatically.

// Wrong: the hook is skipped on some renders
if (isLoggedIn) {
  const [name, setName] = useState('');
}

// Right: always call the hook, then branch on the result
const [name, setName] = useState('');
if (!isLoggedIn) return null;

Follow-up questions interviewers ask next

  • How do you run an effect only when a condition is true?
  • Can you call a hook inside a regular utility function?
Q10Easy2–5 years

What is a custom hook and when would you write one?

30-second answer: A custom hook is a function starting with use that calls other hooks, so you can reuse stateful logic. Each caller gets its own state because it shares code, not data.

A custom hook is a function whose name starts with use and that calls other hooks. It lets you share stateful logic, such as tracking window size or debouncing a value, without sharing any UI.

Each component that calls the hook gets its own independent state: the hook shares code, not data. Extract one when the same combination of state and effects appears in more than one place, or when a component's logic becomes hard to read.

function useDebouncedValue(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);
  return debounced;
}

Follow-up questions interviewers ask next

  • Does two components using the same custom hook share state?
  • How would you test a custom hook?
Q11Medium2–5 years

What does lifting state up mean, and when should you use context instead?

30-second answer: Lift state to the nearest common parent when siblings need it. Use context when many distant components need it, but remember every consumer re-renders when the context value changes.

When two components need the same data, move the state to their closest common parent and pass it down as props. This is lifting state up, and it keeps a single source of truth.

When many components at different depths need the data (theme, current user, locale), passing props through every level becomes tedious, so use context. Context has a cost: every component that reads it re-renders when the value changes, so keep fast-changing state out of a broad context or split it into several smaller ones.

Follow-up questions interviewers ask next

  • How do you stop a context change from re-rendering every consumer?
  • When is a state library better than context?
Q12Medium2–5 yearsOften asked

What causes unnecessary re-renders and how do you prevent them?

30-second answer: A component re-renders on its own state change, a parent render or a context change. Move state down, memoise expensive children and keep props stable, but measure with the Profiler first.

A component re-renders when its state changes, when its parent re-renders or when a context it reads changes. Most re-renders are cheap and harmless, so fix them only when a profiler shows a real problem.

Common fixes: move state down to the component that uses it, pass children so a stable subtree is not rebuilt, wrap expensive pure components in React.memo, keep props referentially stable with useMemo and useCallback, and split large contexts. Measure with the React DevTools Profiler before and after the change.

Follow-up questions interviewers ask next

  • Why can a re-render be harmless even if it happens often?
  • How do inline objects and functions defeat React.memo?
Q13Medium2–5 years

What does React.memo do, and when does it not help?

30-second answer: React.memo skips a re-render when props are shallowly equal. It fails when you pass new objects or functions each render, so keep those props stable.

React.memo wraps a component so it skips re-rendering when its props are shallowly equal to the previous props. It helps when a component is expensive to render and its parent re-renders often with the same inputs.

It does nothing useful when a prop is a new object, array or function on every render, because the shallow comparison sees a new reference each time. Stabilise those props with useMemo or useCallback, otherwise the comparison costs time and saves none.

const Row = React.memo(function Row({ item, onSelect }) {
  return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});

// In the parent: keep onSelect stable so Row can skip renders
const onSelect = useCallback((id) => setSelected(id), []);

Follow-up questions interviewers ask next

  • When would you provide a custom comparison function?
  • Does React.memo stop re-renders caused by state or context inside the component?
Q14Medium2–5 yearsOften asked

How does the useEffect dependency array work, and what goes wrong with it?

30-second answer: The dependency array lists the values an effect uses; the effect re-runs when one changes. Missing deps cause stale values, unstable deps cause loops, and cleanup cancels old work.

The dependency array tells React when to re-run an effect: after the first render and after any render where a listed value changed. An empty array means run once after mounting; omitting the array means run after every render.

Common bugs are missing dependencies, which cause stale values, and unstable dependencies such as an object created inline, which make the effect run on every render and sometimes loop forever. Return a cleanup function to cancel subscriptions, timers and in-flight requests, and let the lint rule tell you what the array should contain.

useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/users/${id}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setUser)
    .catch((err) => {
      if (err.name !== 'AbortError') setError(err);
    });
  return () => controller.abort(); // runs when id changes or on unmount
}, [id]);

Follow-up questions interviewers ask next

  • Why does an object created inline in a dependency array cause a loop?
  • When does the cleanup function run?
Q15Medium2–5 years

When would you use useReducer instead of useState?

30-second answer: Use useReducer when state has several related fields or many kinds of updates, so the logic lives in one pure, testable reducer. Use useState for simple independent values.

useReducer manages state with a pure function (state, action) => newState. It fits when state has several related fields, when the next state depends on the previous one in non-trivial ways or when many different events update the same state.

It keeps the update logic in one testable function and lets you pass dispatch, which has a stable identity, to children instead of many callbacks. For a single independent value, useState is simpler and clearer.

function cartReducer(state, action) {
  switch (action.type) {
    case 'add':
      return [...state, action.item];
    case 'remove':
      return state.filter((i) => i.id !== action.id);
    default:
      return state;
  }
}
const [cart, dispatch] = useReducer(cartReducer, []);
dispatch({ type: 'add', item });

Follow-up questions interviewers ask next

  • Why does dispatch have a stable identity and why does that matter?
  • How would you combine useReducer with context?
Q16Medium2–5 years

What is an error boundary?

30-second answer: An error boundary catches render-time errors in its children and shows a fallback UI. It does not catch errors in event handlers or async code, so wrap independent regions of the page.

An error boundary is a component that catches errors thrown while rendering its children, logs them and shows a fallback UI instead of unmounting the whole app. It is built with a class component that defines static getDerivedStateFromError and componentDidCatch, or with a library wrapper.

Boundaries do not catch errors in event handlers, asynchronous code, server-side rendering or in the boundary itself. Place them around independent regions such as a widget or a route so one failure does not blank the whole page.

Follow-up questions interviewers ask next

  • How would you handle an error thrown inside an onClick handler?
  • Where would you place error boundaries in a real app?
Q17Medium2–5 years

How do React.lazy and Suspense enable code splitting?

30-second answer: React.lazy loads a component through a dynamic import so it becomes its own chunk, and Suspense shows a fallback while it loads. Split by route first, then by heavy components.

React.lazy loads a component with a dynamic import(), so its code is split into a separate chunk and fetched only when it first renders. Suspense shows a fallback while that chunk, or another suspended resource, is loading.

Split by route first, then by heavy components that are not needed for the first paint, such as a chart or a rich-text editor. Over-splitting creates many small requests, so measure the bundle with an analyser and keep the critical path small.

const Chart = React.lazy(() => import('./Chart'));

function Report() {
  return (
    <Suspense fallback={<p>Loading chart...</p>}>
      <Chart />
    </Suspense>
  );
}

Follow-up questions interviewers ask next

  • How do you handle a chunk that fails to load?
  • What else besides components can suspend?
Q18Medium2–5 years

How should you fetch and cache data in a React app?

30-second answer: Raw useEffect fetching leaves you to handle races, caching and errors. A data library such as TanStack Query or SWR handles those, and server fetching removes client work entirely.

Fetching inside useEffect works, but you must handle loading and error state, race conditions (an older response arriving after a newer one), cancellation, caching and retries yourself. That is why many apps use a data library such as TanStack Query or SWR, which provides caching, request deduplication, background refetching and status flags.

In frameworks with server components or route loaders, fetch on the server so the data is part of the initial HTML and the client ships less JavaScript. Choose by where the data is needed and how fresh it must be.

Follow-up questions interviewers ask next

  • How do you avoid a race condition when an input changes quickly?
  • What does stale-while-revalidate mean?
Q19Easy2–5 years

What does StrictMode do?

30-second answer: StrictMode is a development-only check that double-renders components and re-runs effects once to expose impure rendering and missing cleanup. It does nothing in production.

StrictMode is a development-only wrapper that surfaces bugs early. In development it renders components twice and runs effects an extra setup and cleanup cycle on mount, to reveal impure rendering and missing cleanup. It also warns about deprecated APIs.

It has no effect on the production build. If an effect misbehaves when it runs twice, it is usually missing cleanup, for example a subscription that is never closed or a request that is never cancelled.

Follow-up questions interviewers ask next

  • Why does my effect run twice in development?
  • What makes a component render function impure?
Q20HardSenior

What are React Server Components and how do they differ from client components?

30-second answer: Server Components render on the server and ship no JavaScript, and can access data directly but have no state or effects. Client Components hydrate in the browser and handle interactivity.

Server Components render on the server and send their output to the browser without shipping their JavaScript. They can read from a database or use secrets directly, and they cannot use state, effects or browser APIs. Client Components, marked with 'use client', are hydrated in the browser and can be interactive.

The benefit is a smaller client bundle and data fetching close to the data. The trade-off is a new boundary to reason about: props passed from a server component to a client component must be serialisable, and anything interactive needs a client component somewhere below.

Follow-up questions interviewers ask next

  • What can and cannot be passed as props from a server to a client component?
  • How do server components change data-fetching patterns?

How to prepare for a React interview

Reading answers is not enough. A week of focused practice works better:

  1. Build three small things. A filterable todo list (state and keys), a search box that fetches as you type (effects, debouncing, cancelling stale requests) and a long list that you make fast (memoisation and re-render analysis).
  2. Break them on purpose. Use the index as a key and reorder the list. Leave a dependency out of an effect. Seeing the bug makes the explanation stick.
  3. Learn to read the Profiler. Being able to say "I measured, the cause was X and the fix was Y" is the strongest answer to any performance question.
  4. Know the JavaScript underneath. Many React questions are really closure, event loop and promise questions. See the JavaScript interview questions.
  5. Rehearse under pressure. Run a frontend AI mock interview and answer the technical questions out loud.

Common mistakes: reciting definitions without examples, over-using useMemo and useCallback everywhere, and not knowing when an effect is the wrong tool (derived values and event handlers rarely need an effect).