React interview questions and answers

10 questions from the React Interview Mock practice bank, spread across its domains. Pick your answer, then open the explanation to see why each option is right or wrong.

  1. Question 1State and Hooks

    A candidate avoids eval() and models a calculator with a reducer. apply(a, op, b) does the arithmetic.

    function reducer(state, action) {
      switch (action.type) {
        case 'digit':
          return { ...state, display: state.display === '0' ? action.d : state.display + action.d };
        case 'operator':
          return { stored: Number(state.display), op: action.op, display: '0' };
        case 'equals':
          return { stored: null, op: null, display: String(apply(state.stored, state.op, Number(state.display))) };
      }
    }

    The user presses 2 + 3 + 4 =. What is shown, and why?

    • A

      9, because each operator press adds its operand to the running stored total

    • B

      7: the second + overwrites the pending 2 + instead of applying it

    • C

      234, because the digits are joined as strings

    • D

      5, because equals only applies the first operation

    Show the answer and explanation

    Answer: B

    Running this reducer in Node gives 7. A calculator needs explicit state (the current display, the pending op and the stored left operand). On each operator press, if an operation is pending, evaluate it first so chained input like 2 + 3 + 4 works left to right. Interviewers ask candidates to avoid eval or new Function because they run arbitrary code and cannot validate input. They also look for a reducer that is easy to extend with operator precedence or keyboard input.

    Why the other options are wrong

    • A. The operator case overwrites stored with the display value; it never adds to it.

    • C. Each operator resets display to '0' and stores a Number, so the digits never join across operators.

    • D. equals uses whatever is stored when it runs, and by then the first operation has already been lost.

  2. Question 2Architecture and Modern React

    A layout wants every component below it to read the current theme. A teammate writes const theme = useContext(ThemeContext) inside an async Server Component, and it errors. Which two changes are valid fixes? (Choose two.)

    Choose 2.

    • A

      Create a 'use client' ThemeProvider that renders the context provider around {children}

    • B

      Read the theme with useContext in a Client Component somewhere below that provider

    • C

      Mark the async Server Component with 'use server' so it is allowed to call hooks

    • D

      Wrap the useContext call in React.cache() so it runs once per request

    • E

      Call React.createContext inside the Server Component so each request gets its own context

    Show the answer and explanation

    Answer: A and B

    React context is not available in Server Components. The standard pattern is a small Client Component provider (for example ThemeProvider) that the server layout renders around {children}. Server Components inside still render on the server, and any Client Component below the provider can read the value with useContext. To share data between Server Components, use props or cache().

    Why the other options are wrong

    • C. 'use server' marks Server Functions; it never enables hooks in components.

    • D. cache memoises data functions and does not make context available on the server.

    • E. Creating context in a Server Component does not help; it still cannot read context.

  3. Question 3Components and Rendering

    A Vite + React project uses CSS Modules with Vite's default settings. The stylesheet defines .btn-primary { … }, but the button below gets no class. Why?

    import styles from './Button.module.css';
    
    export function Button() {
      return <button className={styles.btnPrimary}>Save</button>;
    }
    • A

      CSS Modules only work with Tailwind, so the import is ignored

    • B

      Keys keep their original names, so read styles['btn-primary'] instead

    • C

      CSS Modules scope classes to one file, so .btn-primary must be marked :global

    • D

      Vite inlines module classes at build time, so they only work in production

    Show the answer and explanation

    Answer: B

    A CSS Module turns each class into a unique, hashed name and exports a mapping object. By default Vite exports the original class names unchanged, so a kebab-case class must be read as styles['btn-primary']. styles.btnPrimary is undefined, and React renders no class at all. Set css.modules.localsConvention: 'camelCaseOnly' if you prefer camelCase keys. Checked against Vite 8.3, which passes localsConvention through unset by default.

    Why the other options are wrong

    • A. CSS Modules work with plain CSS files named *.module.css.

    • C. Local scoping is the point; the generated name is exported for you to use.

    • D. CSS Modules work the same way in dev and production builds.

  4. Question 4Performance and Concurrency

    A component assigns IDs with a module-level counter during render: let next = 0; function Row() { const id = next++; ... }. In production the IDs sometimes skip numbers, and in development every ID is off by one. Why?

    • A

      The counter is shared between browser tabs through module caching, so other tabs consume IDs too

    • B

      React may render more than once per commit: Strict Mode double-renders, and interrupted renders are discarded

    • C

      JavaScript integers overflow after a few thousand increments

    • D

      Hooks reset module variables between renders

    Show the answer and explanation

    Answer: B

    Render must be pure because React may render a component several times and commit only once: Strict Mode renders twice in development, and concurrent rendering can abandon renders that were interrupted or suspended. Mutating outside variables during render therefore leaks the extra attempts. Use useId for IDs, or move side effects into event handlers or effects.

    Why the other options are wrong

    • A. Each tab has its own JavaScript heap and module instances.

    • C. Numbers stay exact up to 2^53; overflow is not the issue.

    • D. Hooks do not touch module scope.

  5. Question 5State and Hooks

    An <Accordion multiple={bool}> must allow only one open section when multiple is false and any number when it is true. Clicking an open section closes it. State is const [openIds, setOpenIds] = useState(() => new Set());. Which toggle meets every requirement?

    • A

      setOpenIds(prev => { prev.has(id) ? prev.delete(id) : prev.add(id); return prev; })

    • B

      setOpenIds(prev => new Set(multiple ? [...prev, id] : [id]))

    • C

      setOpenIds(prev => { const next = new Set(multiple ? prev : []); prev.has(id) ? next.delete(id) : next.add(id); return next; })

    • D

      setOpenIds(prev => { const next = new Set(prev); if (!multiple) next.clear(); next.has(id) ? next.delete(id) : next.add(id); return next; })

    Show the answer and explanation

    Answer: C

    A Set of open ids covers both modes: single mode is the same structure with at most one entry. The two classic mistakes are mutating the Set (React bails out because the reference did not change) and forgetting the close path. Always build a new Set or array when updating state that holds a collection.

    Why the other options are wrong

    • A. It mutates the existing Set and returns the same object. React compares with Object.is, sees no change and skips the re-render.

    • B. An open section can never close: adding an id that is already in a Set does nothing, so clicking it again keeps it open.

    • D. In single mode it clears the Set before checking, so clicking the open section adds it straight back and it never closes.

  6. Question 6Architecture and Modern React

    In TanStack Query v5, ['products', { page: 1, sort: 'price' }] and ['products', { sort: 'price', page: 1 }] refer to the same cache entry.

    • A

      True

    • B

      False

    Show the answer and explanation

    Answer: A

    Query keys are hashed with a stable serializer that sorts object keys, so { page, sort } and { sort, page } match. Array order still matters: ['products', 1] and [1, 'products'] are different keys. Put every variable the query function depends on into the key.

    Why the other options are wrong

    • B. TanStack Query sorts object keys when it hashes, so both keys produce the same hash.

  7. Question 7Components and Rendering

    A file explorer gets a tree such as { id, name, children?: [...] } of any depth. Folders expand and collapse, and files and folders can be added or deleted at any level. Which rendering approach is correct?

    • A
      function Node({ node }) {
        const [open, setOpen] = useState(false);
        if (!node.children) return <li>{node.name}</li>;
        return (
          <li>
            <button onClick={() => setOpen(o => !o)}>{node.name}</button>
            {open && <ul>{node.children.map((c, i) => <Node key={i} node={c} />)}</ul>}
          </li>
        );
      }
    • B
      function Node({ node }) {
        const [open, setOpen] = useState(false);
        if (!node.children) return <li>{node.name}</li>;
        return (
          <li>
            <button onClick={() => setOpen(o => !o)}>{node.name}</button>
            {open && <ul>{node.children.map(c => <Node key={c.id} node={c} />)}</ul>}
          </li>
        );
      }
    • C
      function renderNode(node) {
        const [open, setOpen] = useState(false);
        return <li key={node.id}>{node.name}{open && node.children?.map(renderNode)}</li>;
      }
      // <ul>{tree.children.map(renderNode)}</ul>
    • D
      function Node({ node }) {
        return (
          <li>{node.name}
            <ul>{node.children?.map(c => <li key={c.id}>{c.name}</li>)}</ul>
          </li>
        );
      }
    Show the answer and explanation

    Answer: B

    Trees in React are rendered by a component that renders itself for its children, with stable ids as keys. Rendering the correct version with react-dom/server produced properly nested <ul>/<li> markup at every depth. Interviewers then ask about index keys after a delete, about where expanded state should live, and about accessibility (role="tree", aria-expanded, arrow-key navigation).

    Why the other options are wrong

    • A. The recursion is right, but index keys tie each Node instance (and its open state) to a position. After a delete or insert, the open state moves to a different sibling.

    • C. renderNode is a plain function called in a loop, so its hooks belong to the parent component, and their number changes as folders open and close. That breaks the Rules of Hooks.

    • D. This renders only one level below the node. Grandchildren never appear, and there is no expand or collapse.

  8. Question 8Performance and Concurrency

    A news feed uses infinite scroll. While the user is reading post 40, a WebSocket delivers 3 new posts that belong at the top. Which approach gives the best experience?

    • A

      Prepend the new posts to the list as soon as they arrive

    • B

      Refetch the first page and replace the list with it

    • C

      Hold the new posts aside and show a "3 new posts" pill; tapping it prepends them and scrolls to the top

    • D

      Ignore the real-time posts and show the new ones only after the user pulls to refresh or reloads the whole page

    Show the answer and explanation

    Answer: C

    Feed design questions probe whether you protect the user's reading position. Buffering live items behind a "new posts" banner (as most social apps do) avoids layout jumps. It also works well with cursor-based pagination: older pages keep loading from the bottom cursor while new items wait in a separate buffer at the top.

    Why the other options are wrong

    • A. Inserting content above the reader shifts everything down, so the post they were reading jumps out of view.

    • B. The user loses their place and every page loaded below, and scroll position jumps back to the top.

    • D. This is stable but throws away the real-time requirement; a refresh also loses scroll position and loaded pages.

  9. Question 9State and Hooks

    In a Wordle clone, the answer is THESE and the player guesses GEESE. Wordle colours repeated letters by count: green for the right letter in the right place, yellow only while unmatched copies of that letter remain in the answer, otherwise gray. What should the five tiles show, in order?

    • A

      gray, yellow, green, green, green

    • B

      gray, gray, green, green, green

    • C

      gray, yellow, green, yellow, green

    • D

      gray, yellow, yellow, green, green

    Show the answer and explanation

    Answer: B

    The correct algorithm takes two passes. First mark the greens and count the answer letters that were not matched. Then go left to right, and mark a letter yellow only while its remaining count is above zero, decrementing as you go. Checked in Node: the two-pass scorer gives gray, gray, green, green, green, while both the includes version and the count-without-greens-first version give gray, yellow, green, green, green. This is the edge case interviewers ask about once the basic Wordle grid works.

    Why the other options are wrong

    • A. This is what you get from answer.includes(letter) (or a single pass that counts letters before reserving the greens). The E at position 2 takes a copy of E that the greens at positions 3 and 5 already need.

    • C. S at position 4 matches THESE's S exactly, so it must be green. A guess letter can only be yellow when it is not in the right spot.

    • D. The E at position 3 is in the right spot (THESE also has E there), so it is green, not yellow.

  10. Question 10Architecture and Modern React

    A Server Component imports logView from a 'use server' file and calls await logView(slug) during render. What happens?

    • A

      React sends a POST request to its own server to invoke the action, which adds a network hop

    • B

      It runs as an ordinary async function call on the server, with no network request

    • C

      It throws, because Server Actions can only be invoked from forms or Client Components

    • D

      It is deferred until after the response has streamed, like an analytics beacon sent from the page

    Show the answer and explanation

    Answer: B

    'use server' tells the bundler to give client code a reference that POSTs to the server. Server Components already run on the server, so importing and calling the function is a plain async call. For work that shouldn't block the response, such as logging, Next.js provides after().

    Why the other options are wrong

    • A. On the server, a Server Function is just an async function and is called directly.

    • C. They can be called from Server Components too; they just aren't endpoints in that case.

    • D. Awaiting it blocks the render like any other awaited call; deferral needs after() or similar.

Practise all 720 React questions

Start with the free 15-question diagnostic. It shows where to focus, and your results carry over if you sign up.

Go to React