React Senior 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. Why is React's cache() useful in Server Components?

    Correct answer: It deduplicates calls with the same arguments within a single request

    const getUser = cache(async (id) => db.user.find(id)) - several components in one server render can call getUser(1), and the database query runs once. The cache lives only within the request, so different users' data doesn't mix. Cross-request caching in Next.js is done with 'use cache'.

  2. 2. What is Fiber in React?

    Correct answer: The reconciler architecture: rendering is split into interruptible units of work

    Fiber (React 16+) represents each tree node as a "fiber" object with information about its work. This makes it possible to pause, interrupt and prioritize rendering and reuse work - the foundation of concurrent features (transitions, Suspense). The old stack reconciler walked the tree recursively and couldn't stop.

  3. 3. How does the render phase differ from the commit phase?

    Correct answer: Render is interruptible and can repeat; commit synchronously applies changes to the DOM

    In the render phase, React calls components and computes the diff - it can be interrupted, discarded and restarted, which is why rendering must be pure. In the commit phase, changes are applied to the DOM all at once without interruption, then layout effects run, and after painting - regular effects.

  4. 4. What does concurrent rendering give the user?

    Correct answer: Urgent updates (typing) can interrupt a heavy non-urgent render

    Concurrent doesn't mean multithreaded: JS still runs on one thread. React can prepare several versions of the UI, yield control to the browser and interrupt lower-priority work (transitions) for urgent work. It kicks in when you use startTransition, useDeferredValue and Suspense.

  5. 5. What happens during hydration?

    Correct answer: React attaches handlers and state to the HTML rendered by the server

    hydrateRoot walks the existing DOM, renders components on the client and expects the same markup, so it can simply "bring it to life". Until hydration finishes, the UI is visible but not interactive. If the markup doesn't match, you get a hydration error and the subtree is re-rendered on the client.

  6. 6. Which code in render typically causes a hydration error?

    Correct answer: new Date().toLocaleTimeString() or a typeof window !== 'undefined' branch

    The server and the client must render the same HTML. Time, random numbers, checking window, localStorage and the browser locale produce different results. Show client-only values after mounting (an effect or useSyncExternalStore with getServerSnapshot). For unavoidable text differences (a timestamp) there's suppressHydrationWarning.

  7. 7. What is selective hydration in React 18+?

    Correct answer: Hydrating by Suspense boundaries, prioritizing the one the user clicked

    Each <Suspense> boundary hydrates independently without waiting for all the code. If the user clicks a part that isn't hydrated yet, React raises its priority and replays the event after hydration. Together with streaming, this reduces time to interactivity.

  8. 8. How does streaming SSR (renderToPipeableStream) work?

    Correct answer: HTML is sent in parts: the shell right away, Suspense content when ready

    The server immediately sends the shell with fallbacks, and when the data inside a Suspense boundary is ready, it appends HTML to the stream plus a small script that puts it in place. A slow block no longer delays the whole page. Streaming in the Next.js App Router is built on this.

  9. 9. How do Server Components differ from client components?

    Correct answer: They run only on the server, have no state or effects, and aren't in the bundle

    RSCs can be async and access the database and file system, and their code and dependencies aren't sent to the browser. The result is a serialized tree (the RSC payload). State hooks, effects and event handlers aren't available in them - use client components for interactivity.

  10. 10. What does the 'use client' directive at the top of a file do?

    Correct answer: Marks a boundary: the module and everything it imports go into the client bundle

    'use client' goes at the entry point of a client subtree, not in every file: imported modules automatically become client modules. Client components are still rendered on the server during SSR (into HTML) and hydrated in the browser.

  11. 11. How do you render a Server Component inside a client <Modal>?

    Correct answer: Pass it as children (or another prop) from a Server Component parent

    A client module can't import a server component - the import would make it a client component. But a server parent can render <Modal><ServerCart /></Modal>: ServerCart runs on the server, and Modal receives the ready result as children.

  12. 12. Which props can't be passed from a Server Component to a Client Component?

    Correct answer: Regular functions and class instances - they aren't serializable

    Props cross the network, so they must be serializable: primitives, arrays, plain objects, Date, Map, Set, promises, JSX. You can't pass a function - except Server Functions ('use server'), which turn into a reference for calling.

  13. 13. What's important to remember about 'use server' functions in terms of security?

    Correct answer: They're public HTTP endpoints: check authorization and input inside

    A Server Function can be called with a direct POST request, bypassing the UI. Arguments come from the client and can be forged. Inside the function, check the session and permissions, validate data (e.g. with Zod), and don't rely on the button being visible only to admins.

  14. 14. What is useEffectEvent for?

    Correct answer: To read the latest props and state in an effect without making them dependencies

    Example: a chat connection effect depends on roomId, and on connection you need to show a notification using the current theme. Adding theme to dependencies would reconnect the chat on theme change. const onConnected = useEffectEvent(() => notify(theme)) always sees the fresh theme but isn't reactive.

  15. 15. What does the <Activity mode="hidden"> component (React 19.2) do?

    Correct answer: Hides the subtree, keeping its state and tearing down effects

    The hidden subtree gets display: none, effects are cleaned up, and updates render at low priority. When switched back to visible, state (typed text, scroll) is preserved and effects are recreated. Handy for tabs and pre-rendering screens the user is likely to visit.

  16. 16. What is useImperativeHandle for?

    Correct answer: To expose a limited set of methods to the parent via ref instead of a DOM node

    useImperativeHandle(ref, () => ({ focus, scrollToBottom })) exposes only the needed methods and hides implementation details. An imperative API is an exception for focus, scrolling, animations and media, not a replacement for props.

  17. 17. What does this hook do?

    const useHandler = (f) => {
      const ref = useRef(f);
      ref.current = f;
      return useCallback((...args) => ref.current(...args), []);
    };

    Correct answer: Returns a stable function that always calls the latest version of f

    The callback reference is stable (handy for memo children and effect dependencies), but inside it always sees fresh props and state. Caveat: writing ref.current during render formally breaks render purity; React offers useEffectEvent for this task, and inside effects you'd update the ref in useLayoutEffect.

  18. 18. What is tearing in concurrent rendering?

    Correct answer: Different parts of the UI show different versions of an external mutable store

    If rendering is interrupted and an external store (not React state) changes in the meantime, some components read the old value and others the new one. useSyncExternalStore protects against this. That's why third-party stores should subscribe through it rather than useEffect + useState.

  19. 19. Which of these scenarios causes a memory leak in a React app?

    Correct answer: Subscribing in an effect without unsubscribing in cleanup

    The handler holds a closure with the component's data, which isn't freed after unmounting; repeated mounts accumulate subscriptions. Similar sources: uncleared timers, unbounded global caches, references to detached DOM nodes. Find them with Memory snapshots in DevTools.

  20. 20. What's the most accurate way to find which components are slow during interaction?

    Correct answer: Record a profile in the Profiler and the Performance panel

    The Profiler shows which components rendered, how long it took and why (enable "Record why each component rendered"). The Performance panel shows long tasks, layout and paint. Optimizing blindly leads to unnecessary complexity. For metrics in code there's <Profiler onRender>.

  21. 21. Why doesn't useContext have "selectors", and how do people work around it?

    Correct answer: Context wakes all consumers; split the context or use an external store

    Any change to value re-renders everyone calling useContext, even if they need one field. Workarounds: several narrow contexts, memoized consumers, the use-context-selector library, or a store with selector subscriptions (Zustand, Redux, Jotai).

  22. 22. You need to render a list of 100,000 items. What should you do?

    Correct answer: Virtualize: keep only the visible items in the DOM

    The bottleneck is the number of DOM nodes. Virtualization (TanStack Virtual, react-window) renders a window of visible rows and swaps them while scrolling. memo doesn't reduce the DOM, and timer batches only stretch out the same work. Also consider pagination or server-side filtering.

  23. 23. What happens to an error thrown during render if there's no error boundary above the component?

    Correct answer: React unmounts the whole root tree and reports via onUncaughtError

    An unhandled render error removes the root's entire UI - showing a broken interface is worse than nothing. In React 19, createRoot has onCaughtError and onUncaughtError for logging. That's why boundaries are placed around routes and independent widgets.

  24. 24. Why doesn't an already-shown Suspense fallback appear during a transition inside startTransition?

    Correct answer: React keeps the old UI until the new one is ready instead of swapping in a spinner

    If already displayed content suspends because of an urgent update, React shows the fallback. In a transition it prefers to keep the previous screen (with isPending for an indicator), so skeletons don't "flash". Navigation in Suspense-based routers works this way.

  25. 25. What changed in startTransition in React 19?

    Correct answer: It accepts async functions (Actions) and keeps isPending until they finish

    In React 19, startTransition(async () => { await save(); setState(...) }) is an Action: isPending is true for the whole duration, errors can be handled, and forms with action use this mechanism automatically. Caveat: setState after await must be wrapped in startTransition again.

  26. 26. What's new about callback refs in React 19?

    Correct answer: The callback can return a cleanup function called when the element detaches

    <div ref={node => { const obs = observe(node); return () => obs.disconnect(); }}> - the cleanup runs when the element is removed or the callback changes. Previously React called the callback with null, and cleanup had to be written by hand.

  27. 27. How do you set <title> and <meta> from a component in React 19 without third-party libraries?

    Correct answer: Render them in the component - React hoists them into <head>

    React 19 supports document metadata: <title>, <meta> and <link> anywhere in the tree are moved into <head>, including during SSR and streaming. It also added style precedence (precedence) and async script support. In Next.js, the Metadata API is usually used instead.

  28. 28. Does useMemo guarantee the computation won't repeat with the same dependencies?

    Correct answer: No: React may discard the cache; code must work without useMemo too

    The docs explicitly call useMemo a performance optimization: React may throw away the cache (e.g. for hidden components or in future versions). If code breaks without useMemo, look for a logic problem. For a guaranteed constant value, use useState(() => init) or useRef.

  29. 29. When is it acceptable to call setState directly during render?

    Correct answer: To adjust state when a prop changes, with a guard condition

    The "storing information from previous renders" pattern: if (items !== prevItems) { setPrevItems(items); setSelection(null); }. React immediately re-runs the component's render without painting the intermediate state. It's better than useEffect, but key or computing during render is even better.

  30. 30. When is flushSync justified?

    Correct answer: When the DOM must update synchronously before the next line of code

    Example: you added a message and want to scroll to it immediately - without flushSync, the new DOM node doesn't exist yet. It's also needed when integrating with third-party code like onbeforeprint. It's an expensive operation that breaks batching and concurrent optimizations - use it sparingly.

  31. 31. What is createListenerMiddleware in Redux Toolkit for?

    Correct answer: To run side effects in response to specific actions

    Listener middleware is a lightweight alternative to redux-saga and redux-observable: startListening({ actionCreator: todoAdded, effect: async (action, api) => {...} }). You can wait for other actions (take), cancel tasks, debounce, and work with state before and after the action.

  32. 32. How do you do an optimistic update in RTK Query?

    Correct answer: updateQueryData in onQueryStarted, rolling back via undo()

    dispatch(api.util.updateQueryData('getPost', id, draft => { draft.title = t })) edits the cache with Immer and returns a patch object. In try { await queryFulfilled } catch { patchResult.undo() } the changes are rolled back on error. TanStack Query has a similar approach via onMutate.

  33. 33. What is the signature of a Redux middleware?

    Correct answer: store => next => action => { ... }

    Currying gives the middleware access to getState/dispatch, the next link in the chain next, and the current action. A middleware can log, modify, delay or replace actions (e.g. thunk calls functions instead of passing them on). (state, action) => newState is a reducer.

  34. 34. Why don't you put promises, class instances and functions into the Redux store?

    Correct answer: It breaks serialization, DevTools, state persistence and predictability

    The store should be a plain serializable tree: it's logged, persisted (redux-persist), replayed in time travel and passed from the server during SSR. RTK warns about non-serializable values in dev. Keep non-serializable objects outside the store and store their ids in it.

  35. 35. What is structural sharing in TanStack Query?

    Correct answer: Unchanged parts of a response keep their previous references after a refetch

    When updating data, the library deeply compares the new JSON with the old and reuses references to matching objects. So components that depend on unchanged parts don't re-render, and memo and effect dependencies work correctly.

  36. 36. How do you correctly pass TanStack Query data loaded on the server to client components?

    Correct answer: prefetchQuery on the server, then dehydrate and <HydrationBoundary state>

    The server creates a QueryClient per request, runs prefetchQuery and serializes the cache via dehydrate(queryClient). The client-side HydrationBoundary puts this data into the client cache, and useQuery with the same key gets it immediately without refetching.

  37. 37. Why can't you use a single global QueryClient for all requests on the server?

    Correct answer: One user's cache can leak into another user's response

    The server handles requests from different users in one process, and a shared cache would mix their data. Create a client per request (e.g. via React's cache() in RSC). In the browser, on the contrary, there's one client for the whole app.

  38. 38. How do you properly support request cancellation in TanStack Query?

    Correct answer: Pass the signal from the queryFn argument to fetch

    queryFn: ({ signal }) => fetch(url, { signal }). The library cancels the request if the component unmounts before the response, the key changes, or cancelQueries is called. Without passing signal, only result handling is cancelled while the HTTP request itself continues.

  39. 39. How does useSuspenseQuery differ from useQuery?

    Correct answer: <Suspense> handles loading, a boundary handles errors, data is defined

    The component suspends until data arrives, so there's no need for isPending checks inside, and data isn't undefined. Errors propagate to the error boundary (reset via QueryErrorResetBoundary). Caveats: the enabled option isn't available, and sequential suspensions create request waterfalls.

  40. 40. What must you specify in useInfiniteQuery?

    Correct answer: initialPageParam and a getNextPageParam function

    Data is stored as { pages, pageParams }. getNextPageParam(lastPage) returns the next page's cursor or undefined when there are no more pages (hasNextPage becomes false). Loading more is fetchNextPage(), often triggered by an Intersection Observer.

  41. 41. Do you need Redux or Zustand if server data is already in TanStack Query?

    Correct answer: Often not: little client state remains, and useState and Context are enough

    A large share of "global state" in typical apps is a cache of server data. Once TanStack Query takes it over, the remaining client state (theme, filters, wizard state) is often small. A store is justified for complex client logic: editors, offline mode, complex forms.

  42. 42. "Invalid hook call" error. What's the most likely cause if the component code is correct?

    Correct answer: Two copies of React from different packages ended up in the bundle

    Causes: calling a hook outside a component, mismatched react and react-dom versions, or duplicate React. Hooks are tied to the "dispatcher" of a specific React copy. Check with npm ls react; in monorepos and micro-frontends React is made a singleton (peerDependencies, shared in Module Federation).

  43. 43. What principle underlies React Testing Library?

    Correct answer: Test behavior the way the user sees it: roles, text, labels

    Queries like getByRole('button', { name: 'Save' }) check behavior and accessibility at the same time and don't break when internals are refactored. Interactions are simulated with user-event. Tests of implementation details are brittle and guarantee little.

  44. 44. What are headless UI components, and why are they chosen for design systems?

    Correct answer: Components with logic and accessibility but no styles: the look is entirely yours

    Radix UI, Headless UI and React Aria implement behavior, keyboard handling, focus and ARIA for complex widgets (dialogs, comboboxes, menus), while styling is up to you (Tailwind, CSS Modules). shadcn/ui, for example, is built on this. Writing such widgets from scratch is expensive and risky.

  45. 45. How does key on a wrapper component differ from key inside a list?

    Correct answer: Mechanically it doesn't: changing key always means a new instance with new state

    key is part of a component's identity anywhere. In a list it matches items between renders; outside a list it's used to explicitly reset state (<Chat key={contactId} />). The key must be unique among siblings, not globally.

  46. 46. What are the preload and preinit APIs from react-dom in React 19 for?

    Correct answer: To hint the browser in advance to load fonts, styles and scripts

    preload(href, { as: 'font' }), preinit(href, { as: 'style' }), prefetchDNS and preconnect can be called from components and during SSR - React inserts the matching <link>s into <head> and deduplicates them. This speeds up discovery of critical resources.

  47. 47. Why can React.memo with a custom comparison function be dangerous?

    Correct answer: If not all props are compared, the component shows stale data or callbacks

    arePropsEqual must account for all props, including functions: if you ignore a callback, the component calls its old version with a "frozen" closure. Deep comparison of large data can cost more than the render itself. Stabilizing props is usually the better choice.

  48. 48. How does React 18+ handle setState on an unmounted component?

    Correct answer: It ignores it: the old warning was removed as a false positive

    The warning "Can't perform a React state update on an unmounted component" was removed in React 18: it often fired falsely (e.g. on a request response after leaving the page), and real leaks are forgotten subscriptions, not setState itself. You still need to cancel requests and unsubscribe in cleanup.

  49. 49. What does TanStack Query give you compared to loading data in useEffect with useState?

    Correct answer: Deduplication, caching, retries and race protection

    Hand-rolled loading in an effect quickly accumulates problems: response races, no cache (refetching on every mount), duplicates from several components, manual retries and error handling, desync with the server. The library solves this declaratively via keys.

  50. 50. When does RTK Query remove data from its cache?

    Correct answer: When unused for longer than keepUnusedDataFor

    RTK Query counts hook subscriptions for each endpoint and argument. When no subscribers remain, the keepUnusedDataFor timer starts; if something subscribes again in that time, the data comes from the cache. The TanStack Query counterpart is gcTime.

  51. 51. What does prerender from react-dom/static do differently from streaming SSR?

    Correct answer: It waits for all data and returns complete HTML

    Streaming APIs send HTML as soon as possible and fill in boundaries later. prerender is for build-time or cache-friendly output where waiting for everything is fine.

  52. 52. What is sent to the browser when Server Components render?

    Correct answer: A serialized tree, the RSC payload, with client references

    The payload lets React merge new server output into the existing client tree without losing client state. Server component code itself never ships to the browser.

  53. 53. Why does this component suspend forever (or refetch endlessly)?

    function Profile({ id }) {
      const user = use(fetch(`/api/users/${id}`).then((r) => r.json()));
      return <h1>{user.name}</h1>;
    }

    Correct answer: A new promise each render; use needs a stable one

    After suspending, React re-renders the component, which creates another promise. Pass a promise from a Server Component, a data library or a cache keyed by id.

  54. 54. What does useDeferredValue(query, "") with an initial value change (React 19)?

    Correct answer: The first render returns "", then it updates in the background

    Without initialValue, the first render uses the real value immediately. The initial value is useful when the deferred render is expensive, e.g. a filtered list.

  55. 55. What does the React Compiler need from your code to optimize it safely?

    Correct answer: Code that follows the Rules of React: pure, without mutation

    When it detects rule violations it skips that component instead of risking bugs. The "use no memo" directive opts a component out temporarily.

  56. 56. When is suppressHydrationWarning appropriate?

    <time suppressHydrationWarning>{new Date().toLocaleTimeString()}</time>

    Correct answer: For unavoidable text differences, like timestamps, one level deep

    It doesn't fix the mismatch; React keeps the server text. For content that must differ on the client, render it after mount (effect) or move it to client-only rendering.

  57. 57. What do the onCaughtError and onUncaughtError options of createRoot (React 19) give you?

    Correct answer: Central hooks for reporting caught and uncaught errors

    Previously errors were logged twice and reporting needed a custom boundary everywhere. onRecoverableError covers errors React recovered from, such as hydration mismatches.

  58. 58. Why can importing one icon from a big "barrel" file (index.ts re-exporting everything) hurt?

    Correct answer: Tools may load every re-exported module, slowing builds

    Side effects in any re-exported module prevent tree shaking. Import from specific paths or use tooling like Next.js optimizePackageImports.

  59. 59. A text input at the top of a large page makes the whole page re-render on each keystroke. What is the simplest fix?

    Correct answer: Move the input's state down into a small component

    State changes re-render the component that owns it and its children. Keeping fast-changing state close to where it's used limits the work without any memoization.

  60. 60. Why doesn't <ExpensiveTree /> re-render when ColorPicker state changes here?

    function ColorPicker({ children }) {
      const [color, setColor] = useState("red");
      return <div style={{ color }}>{children}</div>;
    }
    // <ColorPicker><ExpensiveTree /></ColorPicker>

    Correct answer: children was created by the parent, so it's the same object

    Passing JSX as children ("lifting content up") is a memo-free optimization: only the parent that created the element decides when it changes.

  61. 61. What does a test warning "An update was not wrapped in act(...)" mean?

    Correct answer: State changed after the test stopped waiting for updates

    Testing Library wraps its helpers in act already. The warning usually means a pending async update - use await findBy... or waitFor instead of synchronous queries.

  62. 62. Why mock network requests with Mock Service Worker (MSW) rather than mocking fetch in each test?

    Correct answer: It intercepts at the network level, so the real data layer runs

    Tests stay closer to real usage and don't break when you switch from fetch to a library. Handlers can be overridden per test for error cases.

  63. 63. Why does useSyncExternalStore accept a getServerSnapshot argument?

    Correct answer: To give SSR and hydration the same initial value

    Browser-only stores (e.g. localStorage, media queries) have no value on the server. A consistent server snapshot avoids hydration mismatches; the real value is applied right after.

  64. 64. How do you guarantee a module with secrets is never bundled into client code?

    import "server-only";
    export async function getSecretData() { /* uses API keys */ }

    Correct answer: Import server-only, which fails client builds of that file

    'use server' marks Server Functions callable from the client - it does not hide a module. server-only is a build-time guard against accidental imports.

  65. 65. Where does React (17+) attach its event listeners?

    Correct answer: To the root container passed to createRoot

    Attaching to the root made it possible to run several React versions or apps on one page, and e.stopPropagation() now also stops bubbling to native document listeners.

  66. 66. What does <link rel="stylesheet" href="/chart.css" precedence="default" /> inside a component do in React 19?

    Correct answer: React hoists it to <head>, dedupes it and waits for it

    Components can declare their own stylesheets without flashes of unstyled content. precedence controls ordering relative to other stylesheets.

  67. 67. How do you avoid a waterfall when a Server Component needs two independent requests?

    const [user, posts] = await Promise.all([getUser(id), getPosts(id)]);

    Correct answer: Start both before awaiting, e.g. with Promise.all

    Sequential awaits double the latency. Separate Suspense boundaries additionally let the faster part stream in first.

  68. 68. How can a Server Component start a fetch but let a Client Component wait for it?

    // server
    const commentsPromise = getComments(postId);
    return <Comments commentsPromise={commentsPromise} />;
    // client
    const comments = use(commentsPromise);

    Correct answer: Pass the promise as a prop; the client reads it with use

    Promises are serializable props. The page shell renders immediately, and the comments stream in when the promise resolves.

  69. 69. How do you let users retry after an error boundary shows a fallback?

    Correct answer: Reset the boundary's state, e.g. by changing its key

    Built-in error boundaries are class components; the react-error-boundary library adds hooks, reset keys and onReset to refetch or clear bad state.

  70. 70. How do you unit-test a custom hook?

    const { result } = renderHook(() => useCounter(5));
    act(() => result.current.increment());
    expect(result.current.count).toBe(6);

    Correct answer: Render it with renderHook and wrap updates in act

    Hooks need a component context. Use the wrapper option to provide context providers (router, query client) the hook depends on.

  71. 71. Why is storing JSX elements in state usually a bad idea?

    Correct answer: Elements capture props and go stale; store data instead

    Data in state plus rendering from it keeps the UI consistent with the latest props and context. Elements in state also complicate serialization and debugging.

  72. 72. What does Immer's produce give you for deeply nested state updates?

    setState(produce((draft) => { draft.users[3].address.city = "Lviv"; }));

    Correct answer: "Mutating" code on a draft that yields a new immutable object

    Manual spreads for deep paths are verbose and error-prone. Redux Toolkit uses Immer internally; use-immer offers a hook version.

  73. 73. Why might onClick={() => select(item.id)} defeat memo on 1000 list rows?

    Correct answer: Each render makes new functions, so every row's props change

    Pass a stable onSelect (via useCallback) and the id as separate props; the row calls onSelect(id). The React Compiler can automate this.

  74. 74. What happened to propTypes on function components in React 19?

    Correct answer: Runtime checks were removed; use TypeScript or similar

    React 19 silently ignores propTypes. Static types catch the same errors earlier, and schema validation (e.g. Zod) handles external data.

  75. 75. Why are error boundaries still written as classes (or provided by a library)?

    Correct answer: Catching render errors needs class lifecycle methods with no hook equivalent

    Most teams write one reusable boundary (or use react-error-boundary) and place it around routes and independent widgets.