Autocoder

React Hooks Interview Questions and Answers

Last updated 2026-11-19

Hooks are where most React interview rounds are won or lost. The questions are rarely about syntax. They test whether you understand why a value is stale, why an effect runs twice, and when a hook is the wrong tool. This page works through the hooks in depth: the rules, each built-in hook, custom hooks and the bugs that come from misusing them.

It complements the broader React interview questions page, which covers rendering, Server Components and Actions. All answers are for React 19, with notes on 18 where behaviour differs. For the round format, see how to crack a React interview.

Hooks covereduseState, useEffect, useRef, useReducer, useMemo, useCallback, useContext, useLayoutEffect, useSyncExternalStore, useId, custom hooks
VersionReact 19
Questions here18

The two ideas behind almost every hooks question

First, each render is a snapshot: the props, state and functions created in that render keep their values for the whole render, which is why event handlers and effects can see stale data. Second, hooks are identified by call order, which is why they must not be called conditionally. If you can explain those two ideas with a short example, you can reason your way through unfamiliar questions.

Habits that interviewers notice

React Hooks Interview Questions and Answers: questions with worked answers

  1. 1

    What are the Rules of Hooks and why do they exist?

    easy

    Call hooks only at the top level of a component or custom hook, never inside conditions, loops or nested functions, and only from React functions. React stores hook state in a list per component and matches each call by its order, so changing the order between renders attaches state to the wrong hook. The eslint-plugin-react-hooks package enforces both rules. The one exception is use(), which may be called conditionally.

  2. 2

    How does useState work, and what is lazy initialisation?

    easy

    useState returns the current value and a setter, and setting a different value schedules a re-render. If the initial value is expensive to compute, pass a function so it runs only on the first render. Writing useState(compute()) calls compute on every render, even though the result is ignored after the first. React compares new and old values with Object.is, so mutating an object in place does not trigger an update.

    javascript
    const [rows, setRows] = useState(() => parseHugeJson(raw)); // runs once
    setRows(r => [...r, newRow]);                              // new array, not push
  3. 3

    What does the useEffect dependency array do?

    easy

    It controls when the effect re-runs. With no array the effect runs after every render. With an empty array it runs after the first render and cleans up on unmount. With values it runs when any of them changed, compared by Object.is. Every reactive value the effect reads, such as props, state and functions defined in the component, belongs in the array. Omitting some gives stale closures.

  4. 4

    Why is cleanup needed in useEffect? Write a fetch with cancellation.

    medium

    The cleanup runs before the effect re-runs and on unmount. Without it a slow response from an old request can overwrite a newer one, or a subscription keeps firing after the component is gone. Use AbortController for fetch and ignore AbortError.

    javascript
    useEffect(() => {
      const ctrl = new AbortController();
      fetch('/api/users/' + id, { signal: ctrl.signal })
        .then(r => r.json())
        .then(setUser)
        .catch(e => { if (e.name !== 'AbortError') setError(e); });
      return () => ctrl.abort();
    }, [id]);
  5. 5

    Explain a stale closure with a timer example and fix it.

    medium

    The effect below captures count from the render in which it ran. With an empty dependency array the callback always sees 0, so the counter sticks at 1. Fix it with the functional update, which does not read the captured value, or by adding count to the dependencies so the interval is recreated.

    javascript
    useEffect(() => {
      const id = setInterval(() => setCount(c => c + 1), 1000); // not count + 1
      return () => clearInterval(id);
    }, []);
  6. 6

    What is the difference between useRef and useState?

    medium

    Both persist across renders, but changing a ref does not trigger a re-render, while setting state does. Use state for values that appear in the UI. Use a ref for a DOM node, a timer ID, the previous value or any mutable value that rendering does not depend on. Do not read or write ref.current during render, except for lazy initialisation, because it makes rendering impure.

  7. 7

    When should you use useReducer instead of useState?

    medium

    When the next state depends on several related fields, or when many different actions update the same state, such as a form or a checkout flow. A reducer centralises transitions in one pure function, which is easy to test, and dispatch has a stable identity, so you can pass it down without useCallback. For one independent value, useState is simpler.

    javascript
    function reducer(state, action) {
      switch (action.type) {
        case 'add':    return { ...state, items: [...state.items, action.item] };
        case 'remove': return { ...state, items: state.items.filter(i => i.id !== action.id) };
        default:       throw new Error('Unknown action ' + action.type);
      }
    }
    const [cart, dispatch] = useReducer(reducer, { items: [] });
  8. 8

    What do useMemo and useCallback do, and when are they worth using?

    medium

    useMemo caches a computed value and useCallback caches a function identity, both until their dependencies change. They help when the value is genuinely expensive to compute, or when a stable identity is needed for a memo-wrapped child or another hook dependency. They are not free and not semantic guarantees: React may discard the cache. With React Compiler enabled most of them are unnecessary.

  9. 9

    Why does a context consumer re-render so often, and how do you reduce it?

    medium

    Every component calling useContext re-renders when the provider value changes by Object.is. Passing a new object literal each render, such as value={{ user, theme }}, changes it every time. Memoise the value, split unrelated data into separate contexts, or separate state from dispatch contexts. Since React 19 you can render the context itself as the provider, as in ThemeContext value={...}.

  10. 10

    Compare useEffect and useLayoutEffect.

    medium

    useEffect runs after the browser has painted, so it does not block visuals. useLayoutEffect runs synchronously after DOM mutations and before paint, so you can measure an element and update state without a visible flicker, for example positioning a tooltip. It blocks painting, so keep its work tiny, and it does not run on the server, where it logs a warning in older React versions.

  11. 11

    Write a useDebounce custom hook.

    medium

    A custom hook is a function starting with use that calls other hooks to share stateful logic, not state itself: each caller gets its own state. This one returns a value that updates only after the input has been stable for the delay, and cleans up the pending timer.

    javascript
    function useDebounce(value, delay = 300) {
      const [debounced, setDebounced] = useState(value);
      useEffect(() => {
        const t = setTimeout(() => setDebounced(value), delay);
        return () => clearTimeout(t);
      }, [value, delay]);
      return debounced;
    }
  12. 12

    What is useSyncExternalStore for?

    medium

    It subscribes a component to a store that lives outside React, such as a browser API or a state library, in a way that is safe under concurrent rendering and avoids tearing, where different parts of the UI show different versions of the store. You give it a subscribe function, a getSnapshot function that must return a cached value, and optionally a server snapshot. Libraries like Redux and Zustand use it internally.

    javascript
    function useOnline() {
      return useSyncExternalStore(
        cb => {
          window.addEventListener('online', cb);
          window.addEventListener('offline', cb);
          return () => { window.removeEventListener('online', cb); window.removeEventListener('offline', cb); };
        },
        () => navigator.onLine,
        () => true
      );
    }
  13. 13

    What is useId used for?

    medium

    useId generates a string that is stable between server and client renders, so it is safe for linking a label to an input via htmlFor and id, or for aria attributes, without hydration mismatches. Do not use it for list keys, and do not call it once per item in a loop. It is unique per component instance, not a database ID.

  14. 14

    Why does my effect run twice in development?

    medium

    In StrictMode React deliberately mounts, unmounts and re-mounts every component once in development to check that effects clean up properly. It does not happen in production. If the second run causes a visible bug, such as a duplicate subscription or request, the fix is a proper cleanup function or moving the logic out of the effect, not removing StrictMode.

  15. 15

    What is useEffectEvent and which problem does it solve?

    hard

    It lets an effect call a function that always sees the latest props and state without that function being a dependency. Typical case: a chat connection effect should reconnect only when roomId changes, but it also logs using the current theme. Wrapping the logging in useEffectEvent stops theme changes from reconnecting. It was added in React 19.2, and an event function must be called only from effects, not passed around.

  16. 16

    How do useTransition and useDeferredValue differ?

    hard

    Both mark work as non-urgent. useTransition wraps the state update you control: startTransition(() => setQuery(v)) and gives isPending, so the old UI stays responsive. useDeferredValue takes a value you receive, for example from props, and returns a copy that lags behind during urgent updates. Use the first when you own the setter and the second when you do not.

    javascript
    const [isPending, startTransition] = useTransition();
    function onChange(e) {
      setText(e.target.value);                 // urgent: keeps input responsive
      startTransition(() => setFilter(e.target.value)); // can be interrupted
    }
  17. 17

    How do useActionState and useFormStatus differ in React 19?

    hard

    useActionState wraps a form action and returns its latest result, a function to pass to the form, and a pending flag. It lives in the component that owns the form. useFormStatus, from react-dom, lets a child component such as a submit button read the pending state of its parent form without prop drilling. It must be called in a component rendered inside the form, not the same component that renders the form element.

  18. 18

    An effect causes an infinite render loop. How do you diagnose it?

    hard

    The usual cause is an effect that sets state and lists a dependency that the state update changes, often an object or array created inline each render. Check what each dependency is, and whether it is a new reference every time. Fix by depending on primitives, moving the object creation inside the effect, memoising with useMemo, or removing the effect by computing the value during render.

  19. 19

    When is an effect the wrong tool, and what do you use instead?

    hard

    Do not use effects to transform data for rendering, which you compute inline or with useMemo. Do not use them for event responses, which belong in handlers. Do not use them to reset state on a prop change, which a key handles. Do not use them to fetch data in new code when a framework loader, Suspense with use, or TanStack Query is available. Effects are for synchronising with external systems.

Frequently asked questions

Which hooks are asked most in interviews?

useState, useEffect with dependencies and cleanup, useRef, useMemo and useCallback, useContext and useReducer, plus writing one custom hook such as useDebounce or useFetch.

Do I still need useMemo and useCallback in 2026?

Understand them for interviews and for codebases without React Compiler. In compiled code they are mostly unnecessary, but they stay valid for stable identities.

What is the best way to practise hooks questions?

Write each hook from memory in a sandbox, break it on purpose with a stale closure, then fix it. Explaining why it broke is what interviewers listen for.

Are class lifecycle methods still asked?

Occasionally, as a mapping question: componentDidMount, componentDidUpdate and componentWillUnmount correspond to different uses of useEffect.

Related guides

More in Role-wise Interview Questions by Job and Tech Stack

See all in this section