React Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. When does React preserve a component's state between renders?
Correct answer: As long as the same component type stays at the same position
State is tied to a position in the UI tree, not to a variable. If a different type renders in the same place (
<input>instead of<textarea>, another component), the subtree is recreated and state is lost. That's why you must not declare components inside other components: each render creates a new type.2. How do you reset the state of
<EditForm />when switching to another user?Correct answer: Pass
key={userId}- React recreates the componentA new
keytells React it's a different component: the old one unmounts along with its state, and a new one mounts. Resetting via an effect works, but first renders stale data and then fixes it - an extra render and flicker.forceUpdateexists only on classes and doesn't reset state.3. What does
React.memo(Component)do?Correct answer: Skips rendering if props are shallowly equal to the previous ones
memocompares each prop withObject.is. If all are equal, the previous render result is reused. Changes to its own state and context still trigger a render. You can pass a custom comparison function as the second argument.4. Why doesn't
memohelp<List items={data} onSelect={() => select(id)} style={{ gap: 8 }} />?Correct answer: The callback and style object are recreated on each render
An inline function and an object literal are new references on every render, so shallow comparison won't let them through. Stabilize them with
useCallback/useMemo, or move constants outside the component. The React Compiler does this automatically.5. What is
useMemofor?Correct answer: Caching an expensive computation between renders
useMemo(() => filterTodos(todos, tab), [todos, tab])recomputes the value only when dependencies change. The second use is a stable object reference formemochildren or effect dependencies. React may discard the cache, souseMemois an optimization, not a guarantee.6. Why shouldn't you declare a component inside another component?
function Page() { function Row({ item }) { return <li>{item}</li>; } return <ul>{items.map(i => <Row key={i} item={i} />)}</ul>; }Correct answer: Each render creates a new
Rowtype - it gets recreatedTo React,
Rowfrom different renders are different component types, since they're new functions. So the subtree unmounts and remounts every time: state and focus are lost, and the DOM is recreated. Declare components at the top level of the module.7. How are
useCallback(fn, deps)anduseMemorelated?Correct answer:
useCallback(fn, deps)is the same asuseMemo(() => fn, deps)useCallbackcaches the function itself,useMemocaches the result of calling a function.useCallbackdoesn't call the passed function or make it run faster. It's useful when the function is passed to amemocomponent or used as an effect dependency.8. When is
useCallbackactually useful?Correct answer: When a
memochild or an effect receives the functionuseCallbackby itself doesn't speed up code: the function is still created during render, plus there's the cost of comparing dependencies. It makes sense only if someone cares about a stable reference. The function's size doesn't matter.9. When is
useReducerpreferable touseState?Correct answer: With many related fields and complex transitions
useReducergathers update logic into one pure function(state, action) => newState: it's easy to read and test, and handlers only describe what happened (dispatch({ type: 'added' })).dispatchis stable and convenient to pass down. It doesn't make the state global.10. How does
useLayoutEffectdiffer fromuseEffect?Correct answer: It runs after DOM changes but before painting
useLayoutEffectblocks painting, so it suits measuring the DOM and adjusting position (tooltips) without flicker.useEffectruns after painting and doesn't block it - it's the default choice.useLayoutEffectdoesn't run on the server.11. Why does the counter stop at 1?
const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, []);Correct answer: The callback closed over
count = 0from the first renderThe effect with
[]is created once and seescountfrom the first render. Each tick sets0 + 1. Fixes: a functional updatesetCount(c => c + 1)(best), addingcountto dependencies (the interval is recreated), or keeping the value in aref.12. Why does this effect run after every render?
const options = { roomId, serverUrl }; useEffect(() => { const conn = connect(options); return () => conn.close(); }, [options]);Correct answer:
optionsis a new object on every renderDependencies are compared via
Object.is, and a new object literal never equals the previous one. The right way is to create the object inside the effect and depend on primitives:[roomId, serverUrl]. Suppressing the linter is a bad idea.13. How do you avoid a race when loading data in
useEffectifuserIdchanges quickly?Correct answer: An
ignoreflag or anAbortControllerin cleanupResponses can arrive out of order, and an old response overwrites a new one. In cleanup, set
ignore = true(the result is ignored) or callcontroller.abort()(the request is cancelled). Even better, use TanStack Query or framework data loading, where this is solved.14. What's the right way to get
fullNamefromfirstNameandlastNamestored in state?Correct answer: Compute it during render:
const fullName = firstName + ' ' + lastNameValues that can be computed from props and state shouldn't be stored in state. The "state + syncing effect" combo causes an extra render with a stale value and a risk of desync. If the computation is expensive, wrap it in
useMemo.15. Which errors does an error boundary NOT catch?
Correct answer: Errors in event handlers and async code
An error boundary catches errors during render, in constructors and in descendants' lifecycle methods. Errors in
onClick,setTimeoutand promises happen outside render - handle them withtry/catchor put them into state to throw during render. A boundary is a class component withgetDerivedStateFromError;react-error-boundaryis often used.16. What changed about passing
refto function components in React 19?Correct answer:
refis a regular prop, soforwardRefisn't neededIn React 19,
function Input({ ref, ...props })receivesrefdirectly.forwardRefstill works but will be deprecated. Also, a callback ref can now return a cleanup function.17. How do events behave inside a portal
createPortal(child, document.body)?Correct answer: They bubble through the React tree to the React parent
A portal renders DOM elsewhere (modals, tooltips, to escape
overflow: hiddenand stacking contexts), but logically remains part of the React tree: context is available, and events bubble to React ancestors. This is sometimes surprising, e.g. a parent'sonClickfires from a click in the modal.18. What is a higher-order component (HOC)?
Correct answer: A function that takes a component and returns a new one
Example:
withAuth(Page)checks authentication and rendersPageor a redirect. HOCs were popular before hooks. Downsides: "wrapper hell", prop name collisions, complex typing. Today such logic is usually moved into custom hooks.19. What's the idea of the render props pattern?
Correct answer: The component calls a passed function to render
<MouseTracker render={pos => <Cursor {...pos} />} />- the component owns the logic, and the caller decides how to render the result. The function is often passed aschildren. Hooks largely replaced the pattern, but it remains useful, e.g. in virtualized lists and headless components.20. What is the compound components pattern?
Correct answer: Related parts sharing a context:
<Tabs>,<Tabs.Panel>The parent holds state and passes it through Context, and the child parts use it. The user composes the markup, as with native
<select>and<option>, without a dozen configuration props. Radix UI, Headless UI and Reach UI work this way.21. Why do all context consumers re-render on every provider render?
<AuthContext value={{ user, login, logout }}> {children} </AuthContext>Correct answer:
valueis a new object on every provider renderReact compares
valueviaObject.is. An object literal is always new, so every provider render wakes up all consumers. The fix isuseMemofor the value (anduseCallbackfor functions), or splitting the context into parts.22. Why split context into
StateContextandDispatchContext?Correct answer: Components reading only
dispatchdon't re-render when data changesdispatchfromuseReduceris stable and never changes. If you put it into a separate context, "add" and "delete" buttons that read only it won't re-render on every data change. It's a common technique for scaling "reducer + context".23. What does
useTransitiondo?Correct answer: Marks an update as non-urgent, keeping the UI responsive
const [isPending, startTransition] = useTransition(); updates insidestartTransitioncan be interrupted by more urgent ones. For example, switching to a heavy tab doesn't block the UI, andisPendinglets you show an indicator. It has nothing to do with CSS animations.24. When should you use
useDeferredValue?Correct answer: When heavy UI depends on a rapidly changing value
const deferredQuery = useDeferredValue(query)- the input updates immediately, while the heavy list renders with a "lagging" value in the background and is interrupted by new keystrokes. Unlike debounce, there's no fixed delay: on a fast device the lag is almost zero.25. What is automatic batching in React 18+?
Correct answer: Combining multiple
setStatecalls into one render everywhereBefore React 18, updates were batched only in React event handlers. Now
setA(); setB();insidesetTimeout,fetch().then()or native handlers produce one render. If you need to apply an update synchronously (e.g. before measuring the DOM), useflushSync.26. What is
useIdfor?Correct answer: For unique ids that match on server and client
useIdis handy for linkinglabel+input,aria-describedbyand the like.Math.random()would give different values during SSR and hydration, and a global counter breaks with a different render order.useIdisn't suitable for listkeys - keys should come from data.27. What is
useSyncExternalStorefor?Correct answer: Subscribing to an external store without UI "tearing"
The hook takes
subscribe,getSnapshotandgetServerSnapshotand guarantees a consistent value during concurrent rendering (no tearing). Redux, Zustand and similar libraries are built on it. Example: subscribing tonavigator.onLineorlocalStorage.28. How does React 19's
use(promise)differ from regular hooks?Correct answer: It can be called inside conditions; it suspends rendering
usereads the value of a promise or context. Until the promise resolves, the nearest<Suspense>kicks in, and an error goes to the error boundary. Don't create the promise during a client component's render - it'll be new every time; pass it from a Server Component or a caching library.29. What does
useActionStategive you in React 19?Correct answer: The form action's result and an
isPendingflagconst [state, formAction, isPending] = useActionState(action, initialState). Theactionfunction receives the previous state andFormData, and its result becomes the new state - handy for validation errors.formActionis passed to<form action>. It works with Server Functions too.30. What is
useOptimisticfor?Correct answer: Showing the expected result before the server responds
While an action is running,
useOptimisticreturns an optimistic version of the data (e.g. the new message is already in the list). When the action finishes, the real state is shown, and on error the optimistic value simply disappears.31. What does the React Compiler do?
Correct answer: Memoizes components and values at build time
The compiler analyzes code and inserts memoization itself, so manual
useMemo,useCallbackandmemoare mostly unnecessary. It relies on the rules of React (pure renders, immutability) and skips components that break them. In Next.js 16 it's enabled with thereactCompileroption.32. Why is React Hook Form usually faster than forms with controlled fields?
Correct answer: Fields are uncontrolled: typing doesn't re-render the whole form
In a controlled form, every keystroke updates state and re-renders the form. RHF registers fields via
registerand keeps values outside React state, re-rendering only what's subscribed (watch, errors). Validation can run ononChange,onBlurandonSubmit, often with Zod or Yup schemas.33. How do nested
<Suspense>boundaries behave?Correct answer: The fallback of the nearest boundary above fires
Boundary placement determines which parts of the UI appear together. One boundary around the whole page gives one big spinner. Several nested ones let you reveal content progressively: header → main → comments. With streaming SSR, each boundary can arrive as a separate HTML chunk.
34. Where is code splitting with
lazyusually most beneficial?Correct answer: On routes and heavy, rarely needed widgets
Route-based splitting gives the biggest win: the user loads code only for the page they're on. Heavy, rarely needed parts (a rich-text editor, maps) are split out separately. Splitting too finely causes request waterfalls and fallback flicker.
35. What's wrong with this case reducer in
createSlice?todoAdded(state, action) { state.items.push(action.payload); return { ...state, count: state.count + 1 }; }Correct answer: You can't both mutate the draft and return a value
Immer lets you either "mutate" the
statedraft or return an entirely new value - but not both, or Immer throws an error. Herestate.items.push(...)andstate.count += 1are enough.pushis allowed because changes apply to the draft.36. Which actions does
createAsyncThunk('users/fetch', ...)generate?Correct answer:
pending,fulfilledandrejectedThe thunk dispatches
pendingbefore the request, thenfulfilledwith the result orrejectedwith the error. Reducers handle them inextraReducersviabuilder.addCase(fetchUsers.fulfilled, ...). For caching server data, RTK Query is usually a better fit.37. How does RTK Query know which data to refetch after a mutation?
Correct answer: Queries declare
providesTags, mutationsinvalidatesTagsTags link the query cache to mutations:
getPostsprovides[{ type: 'Post', id: 'LIST' }], andaddPostinvalidates thePosttag - active queries with this tag are refetched automatically. It's the counterpart ofinvalidateQueriesin TanStack Query.38. What is RTK Query?
Correct answer: Data fetching and caching in RTK:
createApigenerates hookscreateApidescribes endpoints, and the library generates hooks likeuseGetPostsQueryand manages caching, deduplication, refetching and tag-based invalidation. It solves the same problems as TanStack Query but is built into the Redux infrastructure. It works with GraphQL too, but it isn't a server plugin.39. What does
createEntityAdaptergive you?Correct answer:
{ ids, entities }normalization and CRUD reducersNormalization stores each entity once by id, which simplifies updates and lookups. The adapter provides
addOne,upsertMany,removeOne,setAlland the selectorsselectAll,selectById, and supports sorting.40. Why does this selector cause a re-render on any action in the store?
const done = useSelector(state => state.todos.filter(t => t.done) );Correct answer:
filterreturns a new array every timeuseSelectorruns after every dispatch and compares the result by reference. A new array never equals the previous one. The fix is a memoizedcreateSelectorselector, which returns the same array as long asstate.todoshasn't changed.41. When is Redux (or Zustand) more appropriate than React Context?
Correct answer: When state changes often and you need fine-grained subscriptions
Context is a mechanism for passing a value deep into the tree, not a state manager: when
valuechanges, all consumers re-render; there are no fine-grained subscriptions. For rarely changing data (theme, current user) it's enough. Stores with selectors give fine-grained subscriptions, middleware and DevTools.42. How does
staleTimediffer fromgcTimein TanStack Query?Correct answer:
staleTimeis freshness;gcTimeis how long unused data staysWhile data is fresh, there's no refetch on mount or window focus. After
staleTime, it becomes stale but is still shown from the cache and refreshed in the background.gcTime(formerlycacheTime, 5 minutes by default) starts counting when the query has no observers left - then the data is removed from memory.43. Why does TanStack Query, with default settings, refetch data when you return to the tab?
Correct answer:
staleTime: 0andrefetchOnWindowFocusby defaultBy default, TanStack Query aggressively keeps data up to date: it's considered stale immediately and refetched on mount, window focus and network reconnect. If data rarely changes, increase
staleTimeglobally or for a specific query.44. How do you update a list after successfully creating an item via
useMutation?Correct answer: Call
invalidateQueriesfor['todos']inonSuccessInvalidation marks queries as stale and refetches the active ones. The alternative is to update the cache directly via
setQueryDataif the server returned the new object. Hooks can't be called inside callbacks.45. Which queries does
invalidateQueries({ queryKey: ['todos'] })invalidate?Correct answer: All queries whose key starts with
['todos']Matching is by key prefix by default, which makes hierarchical keys convenient:
['todos']→['todos', 'list', filters]→['todos', 'detail', id]. Exact matching is enabled withexact: true. Keys are often moved into a factory (todoKeys.detail(id)).46. How do you implement an optimistic update via the cache in TanStack Query?
Correct answer:
onMutate- snapshot and edit the cache,onError- roll backcancelQueriesprevents a background request from overwriting the optimistic data. The snapshot fromgetQueryDatais returned fromonMutateas context for rollback. v5 has a simpler option - show the mutation'svariablesin the UI while it'sisPending, without touching the cache.47. How do you run a query only after
user.idis received from another query?Correct answer: Pass
enabled: !!user?.idto the second queryWhile
enabledis false, the query doesn't run (statuspending). Calling a hook conditionally breaks the rules of hooks, and a manualrefetchin an effect is needless complexity.user.idshould be part of the second query's key.48. With pagination, how do you show the old page while the new one loads, instead of a skeleton?
Correct answer:
placeholderData: keepPreviousDataWith a new key (
['projects', page]), the query starts with an empty cache.placeholderDatasubstitutes the previous data while the new data loads, andisPlaceholderDatalets you, for example, disable the "Next" button. In v4 this was thekeepPreviousData: trueoption.49. What does TanStack Query do on a query error by default on the client?
Correct answer: Retries 3 times with increasing delay, then errors
By default
retry: 3, andretryDelaygrows exponentially. Mutations don't retry by default. Retries are configurable with a function, e.g. don't retry 4xx:retry: (count, err) => err.status >= 500 && count < 3.50. Why does
useQueryhave aselectoption?Correct answer: To get part of the data and subscribe only to it
useQuery({ queryKey: ['todos'], queryFn, select: d => d.length })- the cache stores the full response, while the component gets a derived value and subscribes only to it. For a stable reference, move theselectfunction outside the component or memoize it.51. What is wrong with this effect?
const [filtered, setFiltered] = useState([]); useEffect(() => { setFiltered(items.filter((i) => i.visible)); }, [items]);Correct answer: It stores derived data; compute it during render instead
The effect renders once with stale
filtered, then again with the new value.const filtered = items.filter(...)(withuseMemoif expensive) is always in sync.52. Where should code that runs because the user clicked "Buy" go?
Correct answer: In the event handler, not in an effect reacting to state
Effects are for synchronizing with external systems because the component is displayed. Logic caused by a specific interaction belongs to that interaction's handler.
53. Why does this chat effect reconnect when the theme changes?
useEffect(() => { const conn = connect(roomId); conn.on("connected", () => showToast("Connected", theme)); return () => conn.disconnect(); }, [roomId, theme]);Correct answer:
themeis a dependency; move the non-reactive part touseEffectEventEvery reactive value used in an effect must be listed.
useEffectEventlets the handler read the latestthemewithout making the effect depend on it.54. Why does this effect re-run on every render even though
optionslooks the same?const options = { roomId, serverUrl }; useEffect(() => connect(options), [options]);Correct answer: A new object on each render makes the dependency differ
Create the object inside the effect and depend on the primitives (
[roomId, serverUrl]), or memoize it. Objects and functions are compared by reference.55. How should a component subscribe to a browser event like
resize?useEffect(() => { const onResize = () => setWidth(window.innerWidth); window.addEventListener("resize", onResize); return () => window.removeEventListener("resize", onResize); }, []);Correct answer: In
useEffect, unsubscribing in the cleanupWithout cleanup, each mount adds a listener that is never removed (Strict Mode makes this visible). For external stores,
useSyncExternalStoreis the more robust option.56. What makes a good custom hook?
Correct answer: It extracts reusable stateful logic with a clear purpose
Custom hooks share logic, not state. Names describing lifecycle (
useMount) hide intent; prefer names describing what the hook does for the component.57. How does
forwardRefrelate to React 19?Correct answer:
refis now a regular prop, so new code doesn't need itDeclare
function Input({ ref, ...props })and pass it to the DOM element.forwardRefstill works and will be deprecated over time.58. What does
<Suspense fallback={<Spinner />}>show, and when?Correct answer: The fallback while a child is suspended, then the content
Suspense coordinates loading for the whole subtree. Errors are handled by error boundaries, not Suspense.
59. Which state variables are needed here?
const [items, setItems] = useState(list); const [selectedItem, setSelectedItem] = useState(list[0]);Correct answer: Store
selectedId, and find the item initemsIf an item in
itemsis edited, the copy inselectedItembecomes stale. Storing the id avoids duplicated, out-of-sync state.60. How do you avoid many boolean flags like
isSending,isSent,isErrorat once?Correct answer: One
statusstate:'typing' | 'sending' | 'sent' | 'error'Separate booleans allow impossible combinations (sending and sent at once). A single status variable - or a reducer - makes states explicit.
61. Why is this component impure?
let guestCount = 0; function Guest() { guestCount++; return <p>Guest #{guestCount}</p>; }Correct answer: It mutates an outside variable during render
Strict Mode renders twice in development and reveals such bugs. Pass the number as a prop or compute it from data instead.
62. What happens when a component's state changes but the output JSX is identical?
Correct answer: React re-renders but commits no DOM changes
Rendering (calling components) and committing (changing the DOM) are separate. React only touches DOM nodes whose output differs.
63. What does
setCount(5)do ifcountis already 5?Correct answer: React may bail out, as
Object.is(5, 5)is trueReact compares the new state with
Object.is. It may still render the component itself once before bailing out, but children and effects are skipped.64. How do you measure an element's size right after it renders, before the browser paints?
Correct answer: Read it in
useLayoutEffectand set state thereuseLayoutEffectblocks painting until it finishes, avoiding a visible jump. Use it sparingly; it doesn't run on the server.65. Why might a list of controlled inputs lose focus on each keystroke?
{fields.map((f) => <input key={Math.random()} value={f.value} onChange={...} />)}Correct answer: A new random
keyeach render remounts every inputKeys must be stable. A changing key destroys the old DOM node (and its focus and state) and creates a new one.
66. What is the
<Profiler>component for?<Profiler id="Sidebar" onRender={(id, phase, actualDuration) => log(id, actualDuration)}> <Sidebar /> </Profiler>Correct answer: Measuring how often a subtree renders and for how long
It adds some overhead and is disabled in production builds by default. The DevTools Profiler is usually enough for manual investigation.
67. Why is it fine to call
setStateinsideuseEffectthat depends onuserIdto fetch data?Correct answer: Fetching syncs with an external system; just ignore stale responses
Data fetching is a legitimate effect, though frameworks and libraries (TanStack Query, RSC) handle caching and races better than manual effects.
68. How does
useFormStatushelp in a React 19 form?function SubmitButton() { const { pending } = useFormStatus(); return <button disabled={pending}>Save</button>; }Correct answer: A child of
<form>reads the pending state without prop drillingIt must be called from a component rendered inside the
<form>, not in the component that renders the form itself.69. What does
<form action={saveAction}>do in React 19?Correct answer: Calls the function with
FormDataand manages pending stateActions can be client functions or Server Functions. Combined with
useActionStateanduseOptimisticthey cover most form flows without manualonSubmithandling.70. What does
Children.maporcloneElementusage usually signal in modern React?Correct answer: Fragile coupling to children; prefer props or context
Both are marked as legacy APIs. They break when children are wrapped in fragments or other components and make data flow hard to follow.
71. What happens if a parent passes
onChange={() => {}}inline to a memoized child?Correct answer: A new function each render makes
memosee changed propsWrap it in
useCallbackwith correct dependencies, or let the React Compiler memoize it. Withoutmemoon the child, stable callbacks don't matter.72. When does a
useRefvalue change cause a re-render?Correct answer: Never - changing
ref.currentdoesn't trigger renderingRefs are for values that don't affect the output: timer ids, previous values, DOM nodes. If the UI should change, use state.
73. Why shouldn't you read or write
ref.currentduring render?Correct answer: It makes rendering impure; use refs in handlers and effects
The exception is lazy initialization:
if (ref.current === null) ref.current = new Thing(). Otherwise React can't know about the change.74. What is the difference between a controlled and uncontrolled component in a design system?
Correct answer: Controlled ones get their value from props; uncontrolled keep it inside
Good component libraries support both: a
valueprop for full control anddefaultValuefor convenience, never switching between them during a component's life.75. Why can
useEffectwith anasynccallback be a problem?useEffect(async () => { setData(await load()); }, []);Correct answer: An async function returns a promise, not a cleanup function
Define an async function inside the effect and call it:
useEffect(() => { let ignore = false; (async () => { ... })(); return () => { ignore = true }; }, []).