Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 77 ยท Web and Frontend Interview Questions

React Interview Questions

Prepare for React interviews: virtual DOM, reconciliation, rules of hooks, useEffect pitfalls, keys, state versus props and memoization, with stand-ins you can run.

React questions in interviews are rarely about syntax. Interviewers want to know whether you understand what React does between "state changed" and "pixels changed", and whether you can explain why the rules exist. If you only memorized "don't call hooks in loops", you will struggle when asked why.

This lesson covers the questions that appear again and again: the virtual DOM, reconciliation and keys, the rules of hooks, useEffect mistakes, state versus props, and memoization. The real React needs a browser build and cannot be demonstrated line by line here, so the React code below is read-only. Next to it you get small stand-ins written in plain JavaScript that copy the idea (a tree diff, a hook slot array, a stale closure). The stand-ins are not React's source code; they are models that make the behavior easy to see. If you want live React examples, see the React tutorial.

What React does on an update

Re-render Call your component again.
Diff Compare new and old element trees.
Commit Touch only the DOM that changed.

Rendering is cheap. Touching the real DOM is the expensive part.

1 / 2

What is the virtual DOM, and is it faster?

Short answer: the virtual DOM is a plain-object description of the UI that your components return. React keeps the previous description, builds the new one after a state change, compares them and applies only the differences to the real DOM.

The common follow-up is "so it is faster than the DOM?". Be careful. The virtual DOM is not faster than hand-written DOM updates; it is extra work. Its value is that you write declarative code ("the UI for this state looks like this") and React works out the minimal updates for you. Say that, and you sound like someone who has thought about it.

JSX
function Greeting({ name }) {
  // This returns a description (an element tree), not DOM nodes.
  return <h1 className="title">Hello, {name}</h1>;
}
// Roughly: { type: "h1", props: { className: "title", children: ["Hello, ", name] } }

How does reconciliation work?

Reconciliation is the diffing step. Comparing two arbitrary trees optimally is far too slow, so React uses two heuristics:

  1. Different element types produce different trees. If a <div> becomes a <section>, or <Profile> becomes <Settings>, React throws away the old subtree (and its state) and builds a new one.
  2. Keys identify children in lists. Among siblings, React matches old and new children by key, so it can tell "moved" from "replaced".

When the type is the same, React keeps the node and only updates changed props, then recurses into the children. This stand-in diffs two small trees and lists the operations:

JS Stand-in: a tiny tree diff

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The h1 kept its place and only its class changed. The p became a span, so it was replaced. The button is new. That is the whole idea.

Why do lists need keys, and why is the index a bad key?

Short answer: the key is the identity of an item. Without a stable key, React matches children by position, so inserting at the top makes every item look changed, and any state inside items (inputs, focus, animations) ends up attached to the wrong item.

Using the array index as a key is fine for static lists that are never reordered, filtered or inserted into. For anything else, use a stable ID from your data. Never use Math.random(): a new key on every render means every item is destroyed and recreated.

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

// Risky when the list can change order
{todos.map((todo, index) => <TodoRow key={index} todo={todo} />)}

The stand-in below keeps a "typed text" value per row, the way an input remembers its text. It matches rows by index or by id, then we insert a row at the top.

JS Stand-in: index keys versus id keys

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With index keys the text typed into Apples now sits in the Cherries row. That bug is exactly what interviewers hope you can describe.

State versus props

Props are inputs a component receives from its parent. They are read-only for the child. State is data a component owns and can change over time; changing it schedules a re-render. A quick test: if the value can be computed from props or other state, it should not be state at all. Derive it during render.

A frequent follow-up is "how does a child change the parent's data?". The parent passes a callback as a prop, and the child calls it. That pattern is called lifting state up. If you need to pass data through many layers, mention context, but add that context is for rarely changing values such as theme or the current user, not for rapidly changing state.

When explaining state, mention that updates are batched and the new value is only visible on the next render. setCount(count + 1) three times in one handler adds 1, not 3, because all three calls read the same count. Use setCount((c) => c + 1) when the next value depends on the previous one.

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

The rules: call hooks only at the top level of a component or custom hook (not inside conditions, loops or nested functions), and only from React functions. The reason is how hooks are stored. React keeps, for each component, an ordered list of slots. The first useState call reads slot 0, the second reads slot 1, and so on. There are no names, only the call order. If a condition skips a hook on one render, every later hook reads the wrong slot.

JS Stand-in: hooks are slots in an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

When the condition turns false, the skipped hook leaves every later call one slot too early, so age reads "extra" instead of 36. The slots shifted and the component now has the wrong data. Real React detects this and warns, but the mechanism is the same.

useEffect: what interviewers probe

useEffect runs code after render to synchronize with something outside React (a subscription, a timer, the document title, a network request). The classic questions:

  • What does the dependency array do? The effect re-runs when any listed value changed since the last render. An empty array means "only after the first render". No array means "after every render".
  • What is the cleanup function for? It runs before the effect runs again and when the component unmounts. Use it to unsubscribe, clear timers and abort requests.
  • Why does my effect see an old value? A stale closure: the effect function captured the values from the render in which it was created. If you leave a value out of the dependency list, the effect keeps using the old one.
  • Why does it run twice in development? In StrictMode, React mounts, unmounts and mounts again on purpose to expose missing cleanup. It does not happen in production.
JSX
useEffect(() => {
  const id = setInterval(() => {
    console.log(count); // captures count from the render that created this effect
  }, 1000);
  return () => clearInterval(id);
}, []); // BUG: count is used but not listed, so it logs the first value forever

This stand-in reproduces a stale closure without React, using functions created in different "renders":

JS Stand-in: a stale closure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Also be ready for "do you need an effect at all?". Often you do not. Derived values belong in render, user-triggered work belongs in event handlers, and fetching can be done by a library or framework. The React docs call over-using effects a common source of bugs; see You might not need an effect.

Memoization: React.memo, useMemo, useCallback

  • React.memo(Component) skips re-rendering a component if its props are shallowly equal to last time.
  • useMemo(fn, deps) caches a computed value between renders.
  • useCallback(fn, deps) caches a function identity (it is useMemo for functions).

The interview trap: useCallback alone does nothing useful. If a child is not wrapped in React.memo, it re-renders anyway. And memo is defeated if you pass a new object or function on every render, because shallow comparison sees a new reference. Memoization also has a cost (comparisons and memory), so measure first and apply it where renders are genuinely slow.

JS Stand-in: shallow equality and memo

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Be honest about what is real. In the stand-ins, memo, the slots and the diff are simplified models. Real React adds a scheduler, concurrent rendering, fibers and much more. In an interview, describing the model correctly and noting that it is simplified is the right level of detail.

React Router, lifecycle, HOCs and error boundaries

These topics fill the "tell me more about React" half of a React interview. Most are older than hooks, but codebases still contain them, so interviewers ask about them. Companion lesson: React: Redux, Redux Toolkit, Thunks and Context.

How does React Router work?

Short answer: React Router maps the URL to components without a page reload. It uses the History API (pushState) to change the address bar, listens for changes, and renders the route that matches.

The pieces to name (React Router v6 and v7 style):

  • <BrowserRouter> (or createBrowserRouter) provides the routing context.
  • <Routes> and <Route path="/users/:id" element={<User />} /> declare the mapping. Routes can nest, and a parent renders its children through <Outlet />.
  • <Link to="/about"> navigates without a full reload; <NavLink> also knows whether it is the active link, so you can style it.
  • useParams() reads URL parameters (id), useSearchParams() reads the query string, and useNavigate() navigates from code, for example after a form submit.
  • A "protected route" is just a component that checks authentication and renders <Navigate to="/login" /> instead of its children.
JSX
// Read-only: needs react-router
function App() {
  return (
    <BrowserRouter>
      <nav>
        <NavLink to="/">Home</NavLink>
        <NavLink to="/users">Users</NavLink>
      </nav>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/users" element={<UsersLayout />}>
          <Route index element={<UserList />} />
          <Route path=":id" element={<UserDetail />} />
        </Route>
        <Route path="*" element={<NotFound />} />
      </Routes>
    </BrowserRouter>
  );
}

function UserDetail() {
  const { id } = useParams();            // "42" for /users/42
  const navigate = useNavigate();
  return <button onClick={() => navigate("/users")}>Back from user {id}</button>;
}

A follow-up is "why does a deep link like /users/42 give a 404 on a static host?" With BrowserRouter the browser asks the server for /users/42. The server must return index.html for every path so the client router can take over. Hash routing (/#/users/42) avoids that, because the part after # is never sent to the server. For the real router in depth see the React Router tutorial.

What are the class lifecycle methods, and how do hooks replace them?

A class component goes through three phases. constructor and render run first, then mounting finishes with componentDidMount (the DOM exists: fetch data, subscribe). On every update React calls render again and then componentDidUpdate(prevProps, prevState). Before removal it calls componentWillUnmount (clean up timers and subscriptions).

Class method Hook equivalent
componentDidMount useEffect(fn, [])
componentDidUpdate useEffect(fn, [dep])
componentWillUnmount the cleanup function returned by useEffect
shouldComponentUpdate React.memo

Do not call it a perfect mapping. An effect is not "run on mount": it synchronizes with its dependencies, and in development StrictMode runs it twice on purpose to expose missing cleanup. Error boundaries (below) still have no hook equivalent.

PureComponent is a class that implements shouldComponentUpdate with a shallow comparison of props and state, so it skips renders when nothing changed by reference. It is the class-world twin of React.memo, and it has the same trap: mutating an array or object in place keeps the reference, so the component does not update.

What is a higher-order component?

A higher-order component (HOC) is a function that takes a component and returns a new component with extra behavior: withAuth(Page), connect(...)(Component), withRouter(Component). It is the decorator idea applied to components. Hooks and custom hooks replaced most HOCs because they share logic without wrapping the tree and without prop-name collisions. If you write a HOC, forward props, and never create the HOC inside render (a new component type on each render resets the subtree state).

JS Stand-in: a HOC is a function from component to component

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What are error boundaries?

An error boundary is a class component that catches JavaScript errors thrown while rendering its children (and in lifecycle methods and constructors), logs them and shows a fallback UI instead of unmounting the whole app. It defines static getDerivedStateFromError(error) to switch to the fallback and componentDidCatch(error, info) to log.

What they do not catch is a favorite follow-up: errors in event handlers (use try/catch), errors in async code such as promises and setTimeout, errors during server rendering, and errors in the boundary itself. There is no hook for it; people write the class once or use the react-error-boundary package.

JSX
// Read-only
class ErrorBoundary extends React.Component {
  state = { error: null };
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { reportToServer(error, info.componentStack); }
  render() {
    return this.state.error ? <p>Something went wrong.</p> : this.props.children;
  }
}

// <ErrorBoundary><Widget /></ErrorBoundary>
JS Stand-in: a boundary isolates a failing child

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Controlled versus uncontrolled components, and useLayoutEffect

A controlled input gets its value from React state (value={text} plus onChange), so state is the single source of truth and you can validate or transform on every keystroke. An uncontrolled input keeps its value in the DOM; you read it when needed through a ref (or FormData on submit) and may set a starting value with defaultValue. Controlled is the default choice; uncontrolled is simpler for a form you read once, for file inputs (<input type="file"> is always uncontrolled), and for integrating non-React code. Switching an input from uncontrolled to controlled (value going from undefined to a string) triggers a React warning.

useLayoutEffect has the same signature as useEffect but runs synchronously after React updates the DOM and before the browser paints. useEffect normally runs after the paint. Use useLayoutEffect when you must measure the layout (getBoundingClientRect) and change the DOM before the user can see an intermediate frame, for example positioning a tooltip. Otherwise prefer useEffect: layout effects block painting, and they do not run on the server (React warns about them in server rendering).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the array index usually a poor key for a list that can be reordered?

    Keys are identity. If positions shift, an index key points at a different item than before, so state such as typed text follows the position instead of the item.
  2. 2. Why must hooks be called in the same order on every render?

    There are no hook names; React reads state from ordered slots. A conditional hook changes which slot each later call reads.
  3. 3. An effect with an empty dependency array logs an old count forever. What is the cause?

    The callback closes over the values from the render that created it. List count as a dependency or use a functional update.
  4. 4. You wrap a function in useCallback and pass it to a child that is not wrapped in React.memo. What happens?

    A stable function identity only helps if the child skips re-rendering on equal props, which needs React.memo (or the React Compiler).

Summary

  • The virtual DOM is a description of the UI; React diffs the old and new descriptions and updates only what changed. It is a convenience, not a speed trick.
  • Reconciliation replaces a subtree when the element type changes and matches list children by key.
  • Use stable IDs as keys; index keys cause state to follow positions.
  • Hooks are stored in call order, so they must not be conditional.
  • Effects synchronize with the outside world, need cleanup, and suffer from stale closures if dependencies are incomplete.
  • Memoize only when measurement shows a problem, and remember memo depends on stable prop references.
  • React Router matches the URL to routes (Routes, Link, useParams, useNavigate); a static host must serve index.html for deep links.
  • Class lifecycle methods map loosely to useEffect; error boundaries are still class-only and miss event handler, async and server errors.
  • HOCs wrap a component to add behavior; controlled inputs live in state; useLayoutEffect runs before paint, useEffect after.

Next: Node.js and Backend Interview Questions.