25 React Hooks questions with answers for react js roles — 5 easy, 12 medium, 8 hard.
About React Hooks
Hooks are the heart of modern React. Learn useState, useEffect with dependencies and cleanup, useRef, useMemo, useCallback, useReducer and useContext, then move to custom hooks, race conditions in data fetching and the newer APIs: useTransition, useDeferredValue, use, useActionState, useOptimistic and useEffectEvent from React 19.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What are React hooks and what are the rules of hooks?
Hooks are functions like useState and useEffect that let function components use state, side effects, context and other React features. Two rules apply: call hooks only at the top level of a component or custom hook, never inside loops, conditions or nested functions, and call them only from React functions. React relies on the call order being the same on every render to match state to each hook.
02
How does the dependency array of useEffect control when the effect runs?
With no array, the effect runs after every render. With an empty array [], it runs once after the first mount (and twice in development StrictMode to test cleanup). With values like [userId], it runs after mount and again whenever any listed value changes, compared using Object.is. Every reactive value the effect reads, such as props and state, should be included in the array.
useRef returns a mutable object { current } that persists across renders without causing a re-render when changed. It has two main uses: holding a reference to a DOM node, for example to focus an input, and storing mutable values like timer ids, previous values or flags that should not trigger rendering. Do not read or write ref.current during rendering, except for lazy initialisation.
useContext reads the current value of a context created with createContext. React finds the nearest matching Provider above the component and returns its value; if none exists, it returns the default value. Whenever the provider value changes, every component using that context re-renders. In React 19 you can render <ThemeContext value={theme}> directly instead of ThemeContext.Provider, and use(ThemeContext) also works.
05
You see the error 'Rendered more hooks than during the previous render'. What is wrong?
A hook is being called conditionally or after an early return, so the number of hooks changes between renders. For example, if (!user) return null; placed before a useState call. React matches hooks by call order, so this breaks. Move all hook calls to the top of the component before any condition or early return, and put the condition inside the hook logic instead.
06
What is lazy initialisation in useState and when should you use it?
If the initial value is expensive to compute, pass a function instead of the value. React calls it only on the first render.
// runs on every render (wasteful)
const [data, setData] = useState(JSON.parse(localStorage.getItem('cart')));
// runs once
const [data, setData] = useState(() =>
JSON.parse(localStorage.getItem('cart') ?? '[]')
);
07
What is an effect cleanup function and why is it important?
The function you return from useEffect is the cleanup. React runs it before the effect runs again and when the component unmounts. Use it to clear timers, remove event listeners, close WebSocket connections, unsubscribe from stores or abort fetch requests. Without cleanup you get memory leaks, duplicate listeners and state updates on components that are no longer on the screen.
08
What is the difference between useMemo and useCallback?
useMemo caches the result of a calculation between renders, like a filtered list: useMemo(() => filter(items, q), [items, q]). useCallback caches a function definition itself: useCallback(fn, deps), which equals useMemo(() => fn, deps). Both are performance tools, useful when passing values to React.memo children or effect dependencies. With the React Compiler enabled, much of this manual memoisation becomes unnecessary.
09
When should you choose useReducer over useState? Show a small example.
Use useReducer when state has several related fields or many update types, so logic lives in one pure, testable function.
function reducer(state, action) {
switch (action.type) {
case 'added': return [...state, action.item];
case 'removed': return state.filter(i => i.id !== action.id);
default: return state;
}
}
const [cart, dispatch] = useReducer(reducer, []);
dispatch({ type: 'added', item });
10
Write a custom hook to fetch data with loading and error states.
useId generates a unique, stable id for a component instance that matches between server and client rendering. It is used for accessibility attributes, like linking a label's htmlFor to an input's id. Math.random or a global counter would produce different values on the server and the browser, causing hydration mismatches, and would change on every render. useId should not be used as list keys.
12
What do useActionState and useFormStatus do in React 19?
useActionState wraps an action function and returns [state, formAction, isPending]; you pass formAction to a form's action prop and the returned state holds the result, like a validation error. useFormStatus, from react-dom, lets a child component such as a submit button read the pending status of the parent form without prop drilling. Together they remove a lot of manual loading and error state code.
13
Your component fetches data in useEffect and the network tab shows thousands of requests in a loop. What could cause it?
Common causes are a missing dependency array, so the effect runs after every render and its setState triggers another render, or a dependency that is a new object or array each render, like options={{ page: 1 }}. Since Object.is compares by reference, the effect always sees a change. Fix by adding correct dependencies, depending on primitive values, or memoising the object with useMemo.
14
The linter shows a react-hooks/exhaustive-deps warning and a teammate wants to disable the rule. What do you advise?
Disabling it usually hides a stale closure bug. The rule tells you the effect reads a value that can change. Instead, include the dependency, move a function inside the effect, use the updater form of setState so state is not needed, or move non-reactive logic into useEffectEvent. If an object dependency changes every render, create it inside the effect or memoise it. Suppress only with a clear comment.
15
A developer sends an analytics event inside a useEffect that watches a 'submitted' state flag. Is this a good pattern?
No. Logic caused by a specific user action belongs in the event handler, not in an effect. Setting a flag and reacting in an effect adds an extra render, is harder to follow and can fire again on remount in StrictMode. Call sendAnalytics directly in handleSubmit. Effects are for synchronising with external systems because the component is displayed, not for responding to events.
Situation: a new joiner was putting almost all logic into effects, causing bugs. Task: help them build the right mental model. Action: I explained that effects sync with outside systems, while calculations go in render and user actions go in handlers. We refactored one of their components together and I shared the react.dev article on avoiding effects. Result: their next PR had no unnecessary effects.
18
When would you use useLayoutEffect instead of useEffect?
useEffect runs after the browser paints, which is fine for most side effects. useLayoutEffect runs synchronously after DOM changes but before paint, so it is used when you must measure layout and update immediately, for example positioning a tooltip based on its size, to avoid a visible flicker. It blocks painting, so overusing it hurts performance, and it does not run during server rendering.
19
A search box fetches results on every keystroke and sometimes shows results for an older query. How do you fix this race condition?
Responses can arrive out of order, so a slow old request overwrites newer results. Cancel or ignore stale requests in the effect cleanup.
useEffect(() => {
const ctrl = new AbortController();
fetch(`/api/search?q=${q}`, { signal: ctrl.signal })
.then(r => r.json())
.then(setResults)
.catch(() => {});
return () => ctrl.abort();
}, [q]);
Also debounce the input, or use TanStack Query which handles this for you.
Both are concurrent features that keep the UI responsive. useTransition gives you startTransition to mark a state update as non-urgent, plus an isPending flag, so typing stays smooth while a heavy list re-renders. useDeferredValue takes a value and returns a lagging copy that React updates in the background. Use useTransition when you control the setter, and useDeferredValue when you only receive the value as a prop.
use is a React 19 API that reads the value of a promise or a context during render. With a promise, the component suspends until it resolves, showing the nearest Suspense fallback, and errors go to the nearest error boundary. Unlike other hooks, use can be called inside conditions and loops. Promises should come from a framework, cache or server component, not be created fresh on every render.
useOptimistic shows a temporary optimistic state while an async action is running. For example, when a user likes a post, you immediately show the like count increased, call the server, and React automatically reverts to the real state when the action finishes or fails. It makes interfaces feel instant for actions that usually succeed, like sending a chat message or adding to a wishlist.
useEffectEvent, stable since React 19.2, creates a function that always sees the latest props and state but is not reactive, so it does not need to be in the effect's dependency array. Example: a chat effect reconnects when roomId changes, and an onConnected event shows a notification using the current theme. Wrapping the notification in useEffectEvent stops theme changes from reconnecting the socket.
24
How do you expose a custom method like focus() from a child to a parent in React 19?
In React 19, function components receive ref as a normal prop, so forwardRef is no longer needed. Use useImperativeHandle to expose only selected methods.
function SearchInput({ ref }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
clear: () => { inputRef.current.value = ''; }
}));
return <input ref={inputRef} />;
}
// parent: const r = useRef(); <SearchInput ref={r} />; r.current.focus();
useSyncExternalStore subscribes a component to an external, non-React data source, like a browser API or a custom store, in a way that is safe with concurrent rendering. You give it a subscribe function and a getSnapshot function, and optionally getServerSnapshot. It prevents tearing, where parts of the UI show different values of the same store. Libraries like Redux and Zustand use it internally.
Frequently asked questions
How important is React Hooks in React JS interviews?
Hooks are the heart of modern React. Learn useState, useEffect with dependencies and cleanup, useRef, useMemo, useCallback, useReducer and useContext, then move to custom hooks, race conditions in data fetching and the newer APIs: useTransition, useDeferredValue, use, useActionState, useOptimistic and useEffectEvent from React 19.
How should I use the React Hooks sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.