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.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 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. 2. How do you reset the state of <EditForm /> when switching to another user?

    Correct answer: Pass key={userId} - React recreates the component

    A new key tells 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. forceUpdate exists only on classes and doesn't reset state.

  3. 3. What does React.memo(Component) do?

    Correct answer: Skips rendering if props are shallowly equal to the previous ones

    memo compares each prop with Object.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. 4. Why doesn't memo help <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. 5. What is useMemo for?

    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 for memo children or effect dependencies. React may discard the cache, so useMemo is an optimization, not a guarantee.

  6. 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 Row type - it gets recreated

    To React, Row from 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. 7. How are useCallback(fn, deps) and useMemo related?

    Correct answer: useCallback(fn, deps) is the same as useMemo(() => fn, deps)

    useCallback caches the function itself, useMemo caches the result of calling a function. useCallback doesn't call the passed function or make it run faster. It's useful when the function is passed to a memo component or used as an effect dependency.

  8. 8. When is useCallback actually useful?

    Correct answer: When a memo child or an effect receives the function

    useCallback by 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. 9. When is useReducer preferable to useState?

    Correct answer: With many related fields and complex transitions

    useReducer gathers 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' })). dispatch is stable and convenient to pass down. It doesn't make the state global.

  10. 10. How does useLayoutEffect differ from useEffect?

    Correct answer: It runs after DOM changes but before painting

    useLayoutEffect blocks painting, so it suits measuring the DOM and adjusting position (tooltips) without flicker. useEffect runs after painting and doesn't block it - it's the default choice. useLayoutEffect doesn't run on the server.

  11. 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 = 0 from the first render

    The effect with [] is created once and sees count from the first render. Each tick sets 0 + 1. Fixes: a functional update setCount(c => c + 1) (best), adding count to dependencies (the interval is recreated), or keeping the value in a ref.

  12. 12. Why does this effect run after every render?

    const options = { roomId, serverUrl };
    
    useEffect(() => {
      const conn = connect(options);
      return () => conn.close();
    }, [options]);

    Correct answer: options is a new object on every render

    Dependencies 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. 13. How do you avoid a race when loading data in useEffect if userId changes quickly?

    Correct answer: An ignore flag or an AbortController in cleanup

    Responses can arrive out of order, and an old response overwrites a new one. In cleanup, set ignore = true (the result is ignored) or call controller.abort() (the request is cancelled). Even better, use TanStack Query or framework data loading, where this is solved.

  14. 14. What's the right way to get fullName from firstName and lastName stored in state?

    Correct answer: Compute it during render: const fullName = firstName + ' ' + lastName

    Values 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. 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, setTimeout and promises happen outside render - handle them with try/catch or put them into state to throw during render. A boundary is a class component with getDerivedStateFromError; react-error-boundary is often used.

  16. 16. What changed about passing ref to function components in React 19?

    Correct answer: ref is a regular prop, so forwardRef isn't needed

    In React 19, function Input({ ref, ...props }) receives ref directly. forwardRef still works but will be deprecated. Also, a callback ref can now return a cleanup function.

  17. 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: hidden and 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's onClick fires from a click in the modal.

  18. 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 renders Page or 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. 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 as children. Hooks largely replaced the pattern, but it remains useful, e.g. in virtualized lists and headless components.

  20. 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. 21. Why do all context consumers re-render on every provider render?

    <AuthContext value={{ user, login, logout }}>
      {children}
    </AuthContext>

    Correct answer: value is a new object on every provider render

    React compares value via Object.is. An object literal is always new, so every provider render wakes up all consumers. The fix is useMemo for the value (and useCallback for functions), or splitting the context into parts.

  22. 22. Why split context into StateContext and DispatchContext?

    Correct answer: Components reading only dispatch don't re-render when data changes

    dispatch from useReducer is 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. 23. What does useTransition do?

    Correct answer: Marks an update as non-urgent, keeping the UI responsive

    const [isPending, startTransition] = useTransition(); updates inside startTransition can be interrupted by more urgent ones. For example, switching to a heavy tab doesn't block the UI, and isPending lets you show an indicator. It has nothing to do with CSS animations.

  24. 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. 25. What is automatic batching in React 18+?

    Correct answer: Combining multiple setState calls into one render everywhere

    Before React 18, updates were batched only in React event handlers. Now setA(); setB(); inside setTimeout, fetch().then() or native handlers produce one render. If you need to apply an update synchronously (e.g. before measuring the DOM), use flushSync.

  26. 26. What is useId for?

    Correct answer: For unique ids that match on server and client

    useId is handy for linking label + input, aria-describedby and the like. Math.random() would give different values during SSR and hydration, and a global counter breaks with a different render order. useId isn't suitable for list keys - keys should come from data.

  27. 27. What is useSyncExternalStore for?

    Correct answer: Subscribing to an external store without UI "tearing"

    The hook takes subscribe, getSnapshot and getServerSnapshot and guarantees a consistent value during concurrent rendering (no tearing). Redux, Zustand and similar libraries are built on it. Example: subscribing to navigator.onLine or localStorage.

  28. 28. How does React 19's use(promise) differ from regular hooks?

    Correct answer: It can be called inside conditions; it suspends rendering

    use reads 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. 29. What does useActionState give you in React 19?

    Correct answer: The form action's result and an isPending flag

    const [state, formAction, isPending] = useActionState(action, initialState). The action function receives the previous state and FormData, and its result becomes the new state - handy for validation errors. formAction is passed to <form action>. It works with Server Functions too.

  30. 30. What is useOptimistic for?

    Correct answer: Showing the expected result before the server responds

    While an action is running, useOptimistic returns 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. 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, useCallback and memo are 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 the reactCompiler option.

  32. 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 register and keeps values outside React state, re-rendering only what's subscribed (watch, errors). Validation can run on onChange, onBlur and onSubmit, often with Zod or Yup schemas.

  33. 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. 34. Where is code splitting with lazy usually 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. 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 state draft or return an entirely new value - but not both, or Immer throws an error. Here state.items.push(...) and state.count += 1 are enough. push is allowed because changes apply to the draft.

  36. 36. Which actions does createAsyncThunk('users/fetch', ...) generate?

    Correct answer: pending, fulfilled and rejected

    The thunk dispatches pending before the request, then fulfilled with the result or rejected with the error. Reducers handle them in extraReducers via builder.addCase(fetchUsers.fulfilled, ...). For caching server data, RTK Query is usually a better fit.

  37. 37. How does RTK Query know which data to refetch after a mutation?

    Correct answer: Queries declare providesTags, mutations invalidatesTags

    Tags link the query cache to mutations: getPosts provides [{ type: 'Post', id: 'LIST' }], and addPost invalidates the Post tag - active queries with this tag are refetched automatically. It's the counterpart of invalidateQueries in TanStack Query.

  38. 38. What is RTK Query?

    Correct answer: Data fetching and caching in RTK: createApi generates hooks

    createApi describes endpoints, and the library generates hooks like useGetPostsQuery and 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. 39. What does createEntityAdapter give you?

    Correct answer: { ids, entities } normalization and CRUD reducers

    Normalization stores each entity once by id, which simplifies updates and lookups. The adapter provides addOne, upsertMany, removeOne, setAll and the selectors selectAll, selectById, and supports sorting.

  40. 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: filter returns a new array every time

    useSelector runs after every dispatch and compares the result by reference. A new array never equals the previous one. The fix is a memoized createSelector selector, which returns the same array as long as state.todos hasn't changed.

  41. 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 value changes, 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. 42. How does staleTime differ from gcTime in TanStack Query?

    Correct answer: staleTime is freshness; gcTime is how long unused data stays

    While 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 (formerly cacheTime, 5 minutes by default) starts counting when the query has no observers left - then the data is removed from memory.

  43. 43. Why does TanStack Query, with default settings, refetch data when you return to the tab?

    Correct answer: staleTime: 0 and refetchOnWindowFocus by default

    By 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 staleTime globally or for a specific query.

  44. 44. How do you update a list after successfully creating an item via useMutation?

    Correct answer: Call invalidateQueries for ['todos'] in onSuccess

    Invalidation marks queries as stale and refetches the active ones. The alternative is to update the cache directly via setQueryData if the server returned the new object. Hooks can't be called inside callbacks.

  45. 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 with exact: true. Keys are often moved into a factory (todoKeys.detail(id)).

  46. 46. How do you implement an optimistic update via the cache in TanStack Query?

    Correct answer: onMutate - snapshot and edit the cache, onError - roll back

    cancelQueries prevents a background request from overwriting the optimistic data. The snapshot from getQueryData is returned from onMutate as context for rollback. v5 has a simpler option - show the mutation's variables in the UI while it's isPending, without touching the cache.

  47. 47. How do you run a query only after user.id is received from another query?

    Correct answer: Pass enabled: !!user?.id to the second query

    While enabled is false, the query doesn't run (status pending). Calling a hook conditionally breaks the rules of hooks, and a manual refetch in an effect is needless complexity. user.id should be part of the second query's key.

  48. 48. With pagination, how do you show the old page while the new one loads, instead of a skeleton?

    Correct answer: placeholderData: keepPreviousData

    With a new key (['projects', page]), the query starts with an empty cache. placeholderData substitutes the previous data while the new data loads, and isPlaceholderData lets you, for example, disable the "Next" button. In v4 this was the keepPreviousData: true option.

  49. 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, and retryDelay grows 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. 50. Why does useQuery have a select option?

    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 the select function outside the component or memoize it.

  51. 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(...) (with useMemo if expensive) is always in sync.

  52. 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. 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: theme is a dependency; move the non-reactive part to useEffectEvent

    Every reactive value used in an effect must be listed. useEffectEvent lets the handler read the latest theme without making the effect depend on it.

  54. 54. Why does this effect re-run on every render even though options looks 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. 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 cleanup

    Without cleanup, each mount adds a listener that is never removed (Strict Mode makes this visible). For external stores, useSyncExternalStore is the more robust option.

  56. 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. 57. How does forwardRef relate to React 19?

    Correct answer: ref is now a regular prop, so new code doesn't need it

    Declare function Input({ ref, ...props }) and pass it to the DOM element. forwardRef still works and will be deprecated over time.

  58. 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. 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 in items

    If an item in items is edited, the copy in selectedItem becomes stale. Storing the id avoids duplicated, out-of-sync state.

  60. 60. How do you avoid many boolean flags like isSending, isSent, isError at once?

    Correct answer: One status state: '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. 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. 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. 63. What does setCount(5) do if count is already 5?

    Correct answer: React may bail out, as Object.is(5, 5) is true

    React 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. 64. How do you measure an element's size right after it renders, before the browser paints?

    Correct answer: Read it in useLayoutEffect and set state there

    useLayoutEffect blocks painting until it finishes, avoiding a visible jump. Use it sparingly; it doesn't run on the server.

  65. 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 key each render remounts every input

    Keys must be stable. A changing key destroys the old DOM node (and its focus and state) and creates a new one.

  66. 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. 67. Why is it fine to call setState inside useEffect that depends on userId to 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. 68. How does useFormStatus help 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 drilling

    It must be called from a component rendered inside the <form>, not in the component that renders the form itself.

  69. 69. What does <form action={saveAction}> do in React 19?

    Correct answer: Calls the function with FormData and manages pending state

    Actions can be client functions or Server Functions. Combined with useActionState and useOptimistic they cover most form flows without manual onSubmit handling.

  70. 70. What does Children.map or cloneElement usage 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. 71. What happens if a parent passes onChange={() => {}} inline to a memoized child?

    Correct answer: A new function each render makes memo see changed props

    Wrap it in useCallback with correct dependencies, or let the React Compiler memoize it. Without memo on the child, stable callbacks don't matter.

  72. 72. When does a useRef value change cause a re-render?

    Correct answer: Never - changing ref.current doesn't trigger rendering

    Refs are for values that don't affect the output: timer ids, previous values, DOM nodes. If the UI should change, use state.

  73. 73. Why shouldn't you read or write ref.current during 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. 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 value prop for full control and defaultValue for convenience, never switching between them during a component's life.

  75. 75. Why can useEffect with an async callback 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 }; }, []).