Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

React Hooks Interview Questions: useState, useEffect, useRef, useMemo and Custom Hooks

12 React hooks interview questions with code and explanations: rules of hooks, useState batching and functional updates, useEffect dependencies and cleanup, useLayoutEffect, useRef, useContext, useReducer, useMemo, useCallback, custom hooks and stale closures.

Sumit KumarUpdated Oct 12, 20267 min readReact
React Hooks Interview Questions: useState, useEffect, useRef, useMemo and Custom Hooks

Almost every React interview spends time on hooks, because they reveal whether you understand how components render and re-render. Here are 12 React hooks interview questions for fresher-to-mid roles, with answers, code and the explanation interviewers want to hear.

React hooks grouped by purpose: state with useState and useReducer, effects with useEffect and useLayoutEffect, refs and context with useRef and useContext, and performance with useMemo and useCallback

New to React? Start with React interview questions for freshers.

Basics and rules#

Q1. What are hooks and what are the rules of hooks?#

Answer: hooks are functions starting with use that let function components use state, effects, context and other React features. There are two rules:

  1. Only call hooks at the top level: not inside loops, conditions or nested functions.
  2. Only call hooks from React functions: function components or custom hooks.

Why: React stores hook state in a list per component and matches each call by its order. If a hook is skipped on one render, every later hook reads the wrong state.

JSX
// Wrong: the hook order changes when isLoggedIn changes
if (isLoggedIn) {
  const [name, setName] = useState("");
}

// Right: always call the hook, put the condition inside
const [name, setName] = useState("");
if (isLoggedIn) { /* use name */ }

Q2. Why does this counter only increase by 1?#

JSX
function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = () => {
    setCount(count + 1);
    setCount(count + 1);
    setCount(count + 1);
  };
  return <button onClick={handleClick}>{count}</button>;
}

Answer: state is a snapshot for each render. All three calls read the same count (0) and set it to 1. React also batches the updates into one re-render. Use the functional update form when the new state depends on the previous one:

JSX
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1); // now increases by 3

Since React 18, batching also applies inside promises, timeouts and native event handlers (automatic batching).

Q3. Why must state be updated immutably?#

Answer: React compares the old and new state with Object.is. If you mutate an object and pass the same reference, React thinks nothing changed and may skip the re-render.

JSX
// Wrong: same array reference
todos.push(newTodo);
setTodos(todos);

// Right: new array and new object
setTodos([...todos, newTodo]);
setUser({ ...user, name: "Asha" });
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));

Effects#

Q4. How does the useEffect dependency array work?#

Dependency arrayEffect runs
OmittedAfter every render
[]Once after the first render (mount)
[a, b]After mount and whenever a or b changes

Every value from the component that the effect uses (props, state, functions) should be in the array. Leaving one out causes bugs with stale values. The eslint-plugin-react-hooks rule exhaustive-deps warns about this.

Q5. What is the cleanup function in useEffect? Give an example#

Answer: the function returned from an effect runs before the effect runs again and when the component unmounts. Use it to undo side effects: remove listeners, clear timers, cancel requests and close sockets.

JSX
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then((res) => res.json())
      .then(setUser)
      .catch((err) => {
        if (err.name !== "AbortError") console.error(err);
      });

    return () => controller.abort(); // cancel the old request
  }, [userId]);

  return <p>{user?.name}</p>;
}

Without the cleanup, a slow response for an old userId could overwrite a newer one (a race condition).

Strict Mode

In development, React 18 Strict Mode mounts, unmounts and remounts components once to expose missing cleanups. If your effect runs twice in dev, that's expected, not a bug in React.

Q6. What is the difference between useEffect and useLayoutEffect?#

useEffectuseLayoutEffect
RunsAfter the browser paintsAfter DOM updates, before paint
Blocks paint?NoYes
Use forData fetching, subscriptions, loggingMeasuring layout and adjusting it without flicker (tooltips, scroll position)

Default to useEffect. Reach for useLayoutEffect only when you see a visual flicker.

Refs, context and reducers#

Q7. What is useRef used for? How is it different from state?#

Answer: useRef returns a mutable object { current } that persists across renders. Changing ref.current does not cause a re-render. Two common uses:

JSX
function SearchBox() {
  const inputRef = useRef(null);          // 1. access a DOM node
  const renderCount = useRef(0);          // 2. keep a mutable value

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  renderCount.current += 1;               // no re-render triggered

  return <input ref={inputRef} placeholder="Search" />;
}

Use state for values shown in the UI; use refs for values the UI doesn't depend on (timer IDs, previous values, DOM nodes).

Q8. When would you use useReducer instead of useState?#

Answer: use useReducer when state has several related fields, the next state depends on the previous one in complex ways, or many event handlers update the same state. The update logic moves into a pure, testable function.

JSX
function reducer(state, action) {
  switch (action.type) {
    case "fetch_start":   return { ...state, loading: true, error: null };
    case "fetch_success": return { loading: false, error: null, data: action.data };
    case "fetch_error":   return { ...state, loading: false, error: action.error };
    default: return state;
  }
}

const [state, dispatch] = useReducer(reducer, { loading: false, data: null, error: null });
dispatch({ type: "fetch_start" });

Q9. How does useContext work, and what is its performance catch?#

Answer: context passes a value through the tree without prop drilling. A component reads it with useContext.

JSX
const ThemeContext = createContext("light");

function App() {
  const [theme, setTheme] = useState("dark");
  const value = useMemo(() => ({ theme, setTheme }), [theme]);
  return (
    <ThemeContext.Provider value={value}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function ThemedButton() {
  const { theme } = useContext(ThemeContext);
  return <button className={theme}>Save</button>;
}

The catch: every component using the context re-renders when the value changes. Passing a new object literal on each render (value={{ theme }}) re-renders all consumers every time, so memoize the value and split large contexts into smaller ones.

Performance and custom hooks#

Q10. What is the difference between useMemo and useCallback?#

JSX
// useMemo caches a computed VALUE
const sortedProducts = useMemo(
  () => [...products].sort((a, b) => a.price - b.price),
  [products]
);

// useCallback caches a FUNCTION reference
const handleSelect = useCallback((id) => {
  setSelectedId(id);
}, []);

// useCallback(fn, deps) is the same as useMemo(() => fn, deps)

Use them when a computation is genuinely expensive, or when a stable reference matters: passing a callback to a component wrapped in React.memo, or using a value in another hook's dependency array. Wrapping everything adds overhead and complexity without benefit. More in React performance interview questions.

Q11. Write a custom hook. Why are custom hooks useful?#

Answer: a custom hook is a function starting with use that calls other hooks. It lets components share stateful logic (not state itself: each component calling the hook gets its own state).

JSX
function useDebounce(value, delay = 300) {
  const [debounced, setDebounced] = useState(value);

  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);
  }, [value, delay]);

  return debounced;
}

function Search() {
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebounce(query, 400);

  useEffect(() => {
    if (debouncedQuery) fetchResults(debouncedQuery);
  }, [debouncedQuery]);

  return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}

Other common custom hooks in interviews: useFetch, useLocalStorage, usePrevious, useOnClickOutside and useWindowSize.

Q12. What is a stale closure in hooks? How do you fix it?#

JSX
function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(count + 1);   // always reads count = 0
    }, 1000);
    return () => clearInterval(id);
  }, []);                    // effect created once

  return <p>{count}</p>;   // stuck at 1
}

Answer: the interval callback was created during the first render, so it closes over count = 0 forever. Fixes:

  • Use a functional update: setCount((c) => c + 1) (best here).
  • Add count to the dependencies, so the interval is recreated each time.
  • Store the latest value in a ref and read ref.current in the callback.

Closures themselves are covered in closures and scope interview questions.

Quick revision#

HookPurposeRe-renders when it changes?
useStateLocal stateYes
useReducerComplex state logicYes
useEffectSide effects after paint-
useLayoutEffectDOM measurement before paint-
useRefDOM access, mutable valuesNo
useContextRead shared valuesYes, when the value changes
useMemo / useCallbackCache values / functions-

Key takeaways#

  • Hooks rely on call order: call them at the top level, never conditionally.
  • State is a per-render snapshot; use functional updates when the next state depends on the previous one.
  • Include every used value in effect dependencies and always clean up subscriptions, timers and requests.
  • useRef holds values without re-rendering; useReducer organises complex state.
  • Custom hooks share logic, not state; stale closures are fixed with functional updates, correct dependencies or refs.