State Management 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 do Redux, Zustand and similar libraries subscribe through useSyncExternalStore?

    Correct answer: It guarantees a consistent snapshot during concurrent rendering (no tearing)

    With concurrent rendering React may pause a render; if an external store changes meanwhile, some components could read old values and others new ones. useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) prevents that and supports SSR.

  2. 2. What's wrong with this getSnapshot?

    useSyncExternalStore(subscribe, () => ({ items: store.items }));

    Correct answer: It returns a new object on each call

    React calls getSnapshot repeatedly and compares results with Object.is; a fresh object means "changed" every time, causing infinite re-renders. Return a cached/immutable value from the store (or a primitive).

  3. 3. What's the difference between the "subscribe to a selector" model (Redux, Zustand) and Context?

    Correct answer: A store notifies components and each re-renders only if its selected slice changed

    Context has no selectors: any value change re-renders every consumer. Stores run each subscriber's selector and compare results, so updates are fine-grained. Libraries like use-context-selector emulate this on top of Context.

  4. 4. Where should the state of a list filter (search text, sort, page) ideally live in a routed app?

    Correct answer: In the URL search params

    The URL is state too. Filters in ?q=&sort=&page= make links shareable and history meaningful, and loaders/query keys can derive from them. Debounce typing and replace (not push) history entries for every keystroke.

  5. 5. Which classification of state helps pick tools in a large app?

    Correct answer: Server cache, URL, form, local and global client state

    Each kind has a natural home: server cache - TanStack Query/RTK Query/SWR/loaders; URL - the router; forms - local state or a form library; UI - useState; truly global client state - Context or a store. Putting everything into one store makes it the bottleneck.

  6. 6. How do you prevent consumers of a CartContext from re-rendering when only dispatch-style actions are used?

    Correct answer: Provide state and actions in separate contexts

    Buttons that only call addItem read CartActionsContext (memoized once), so cart changes don't re-render them. Only components that read CartStateContext update.

  7. 7. Why are Context providers in the Next.js App Router placed in a separate client component?

    Correct answer: createContext is a client-only API

    A 'use client' providers.tsx wraps children, which stay server components because they're passed as props. Place providers as deep as possible so more of the tree remains static.

  8. 8. Why is "one big AppContext with all state" considered an anti-pattern?

    Correct answer: Any change re-renders every consumer

    Typing in a search box re-renders the cart and the header. Split by domain and update frequency, colocate state, and move high-frequency shared state into a store with selectors.

  9. 9. What does use(Context) in React 19 add compared to useContext?

    Correct answer: It can be called conditionally (e.g. after an early return)

    use isn't bound by the "top-level only" rule, so if (!show) return null; const theme = use(ThemeContext) works. Otherwise it reads the same nearest provider and doesn't add selectors.

  10. 10. What is createListenerMiddleware for?

    Correct answer: Running side effects in response to actions

    A lightweight alternative to sagas: startListening({ actionCreator: todoAdded, effect: async (action, api) => {...} }). Effects can wait for other actions (take), cancel, debounce and read state before/after.

  11. 11. What does combineSlices add to Redux Toolkit?

    Correct answer: Lazy injection of slices for code-split features

    const rootReducer = combineSlices(authSlice) and later rootReducer.inject(lazySlice) from a lazily loaded module. Typed selectors (slice.selectors) handle the possibility that the slice isn't injected yet.

  12. 12. Why shouldn't you put promises, class instances or functions into the Redux store?

    Correct answer: It breaks serializability, DevTools and SSR transfer

    The store should be plain data that can be logged, saved and replayed. Keep non-serializable objects outside (e.g. in a module or listener) and store ids/serializable snapshots instead.

  13. 13. What does a memoized selector from createSelector need to be effective with arguments?

    const selectByCategory = createSelector(
      [(s) => s.products, (s, category) => category],
      (products, category) => products.filter((p) => p.category === category),
    );

    Correct answer: Input selectors that return stable references

    The default cache stores the latest inputs, so alternating arguments in several components ('books', 'toys') recomputes every time. Create a selector per component (useMemo(makeSelector, [])) or configure a larger cache (weakMapMemoize is the default in Reselect 5).

  14. 14. Why does Redux recommend the "ducks"/feature-folder structure with createSlice?

    Correct answer: Everything for a feature lives in one place

    The style guide recommends organizing by feature and using createSlice so a single file owns a slice's logic. Cross-feature reactions go through extraReducers or listeners rather than reaching into other slices.

  15. 15. A reducer for orders/placed must also clear the cart slice. What's the idiomatic way?

    Correct answer: Let the cart slice handle orders/placed in its extraReducers

    Reducers can't dispatch or touch other slices. Many reducers responding to one event is the intended Redux model: the action describes what happened, and each slice decides how to react.

  16. 16. Why is a module-level Zustand store dangerous in SSR (Next.js)?

    Correct answer: One module instance is shared by all requests

    The Next.js guide recommends creating the store per request with createStore and passing it through a Context provider, then reading it with useStore(storeApi, selector). In a purely client SPA a global store is fine.

  17. 17. How do you persist only some fields of a Zustand store and handle schema changes?

    Correct answer: Use partialize to pick fields and version + migrate for old data

    persist(fn, { name, partialize: (s) => ({ cart: s.cart }), version: 2, migrate: (old, v) => ... }). Without migrations, a renamed field leaves broken data in users' storage.

  18. 18. How do you react to Zustand changes outside React (e.g. sync to an analytics SDK)?

    Correct answer: With useStore.subscribe(listener)

    subscribe returns an unsubscribe function. The subscribeWithSelector middleware lets you subscribe to a specific selector with an equality function - handy for side effects tied to one field.

  19. 19. What does the devtools middleware give a Zustand store?

    Correct answer: Redux DevTools with an action log and time travel

    create(devtools((set) => ...)) and naming updates (set(fn, false, 'cart/add')) make the history readable. It's one reason teams pick Zustand: lightweight yet debuggable.

  20. 20. Zustand vs Redux Toolkit: when is RTK the stronger choice?

    Correct answer: Large teams that need strict conventions

    Zustand is minimal and flexible; RTK enforces a structured, event-driven model with strong tooling. Both are fine choices - the deciding factors are team size, conventions and whether you'll use RTK Query.

  21. 21. How do you implement an optimistic update with the cache in TanStack Query?

    Correct answer: onMutate to update, onError to roll back

    cancelQueries prevents an in-flight refetch from overwriting the optimistic data; the snapshot from getQueryData is returned as context for rollback. v5 also has a simpler approach: render variables while the mutation isPending, without touching the cache.

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

    Correct answer: Unchanged parts of a refetched response keep their old references

    The new JSON is deep-compared with the old one and equal subtrees reuse references, so memo components and effect dependencies don't react to identical data. It can be disabled for huge non-JSON data.

  23. 23. Why are query key factories recommended?

    export const todoKeys = {
      all: ["todos"] as const,
      lists: () => [...todoKeys.all, "list"] as const,
      list: (filters: Filters) => [...todoKeys.lists(), filters] as const,
      detail: (id: number) => [...todoKeys.all, "detail", id] as const,
    };

    Correct answer: Keys stay consistent and prefix invalidation works

    Typos in hand-written keys silently break caching and invalidation. A factory gives one source of truth: invalidateQueries({ queryKey: todoKeys.lists() }) refreshes every list but not details.

  24. 24. How do you pass server-prefetched TanStack Query data to client components in the Next.js App Router?

    Correct answer: dehydrate plus <HydrationBoundary>

    A per-request QueryClient prefetches and serializes the cache; the client HydrationBoundary puts it into the browser cache, so useQuery with the same key renders immediately without a refetch.

  25. 25. Why must you not create one global QueryClient for all requests on the server?

    Correct answer: One user's data could be served to another

    Server processes handle many users. Create the client per request (e.g. React cache() in RSC). In the browser, by contrast, one client for the whole app is correct.

  26. 26. What does useSuspenseQuery change?

    Correct answer: <Suspense> handles the loading state

    No isPending checks inside the component. Caveats: enabled isn't available, and sequential suspending queries create waterfalls - prefetch or use useSuspenseQueries for parallel loading.

  27. 27. What must you configure for useInfiniteQuery?

    Correct answer: initialPageParam and getNextPageParam

    Data is { pages, pageParams }; getNextPageParam(lastPage) returns the next cursor or undefined when done (hasNextPage becomes false). fetchNextPage is often triggered by an IntersectionObserver.

  28. 28. How do you cancel an in-flight request when a query becomes unused in TanStack Query?

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

    queryFn: ({ signal }) => fetch(url, { signal }). The library aborts when the component unmounts before the response, the key changes, or cancelQueries is called. Without signal only result handling is cancelled.

  29. 29. What does the select option of useQuery give you?

    const count = useQuery({ queryKey: ["todos"], queryFn, select: (d) => d.length });

    Correct answer: A derived value that limits re-renders

    The cache keeps the full response while each component subscribes to its own projection. Keep the select function stable (define it outside or memoize it) so it isn't re-run on every render.

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

    Correct answer: updateQueryData in onQueryStarted, then undo()

    dispatch(api.util.updateQueryData('getPost', id, (draft) => { draft.title = t })) patches the cache via Immer and returns a patch object; try { await queryFulfilled } catch { patch.undo() } rolls it back.

  31. 31. How does RTK Query decide which tagged queries to refetch with id-level tags?

    providesTags: (result) => [
      ...(result?.map(({ id }) => ({ type: "Post" as const, id })) ?? []),
      { type: "Post", id: "LIST" },
    ],

    Correct answer: It refetches only queries providing that exact tag

    Editing post 5 invalidates { type: 'Post', id: 5 } (detail and lists containing it), while adding a post invalidates { type: 'Post', id: 'LIST' }. Fine-grained tags avoid refetching everything.

  32. 32. What is transformResponse used for in an RTK Query endpoint?

    Correct answer: Reshaping the API response before it's cached

    transformResponse: (res) => res.data.items keeps the API quirks out of components and the cache. For normalized caches you can combine it with createEntityAdapter.

  33. 33. How do you write the result of a mutation directly into a cached query without refetching (pessimistic update)?

    Correct answer: Await queryFulfilled, then updateQueryData

    A pessimistic update waits for the server and then patches the cache - no extra request, but the UI updates only after the response. Optimistic updates patch first and undo on failure.

  34. 34. Can RTK Query and createSlice state coexist in one store?

    Correct answer: Yes: the API slice is just another reducer

    Slices can listen to endpoint actions (builder.addMatcher(api.endpoints.login.matchFulfilled, ...)) - e.g. to store a token after login - while server data stays in the RTK Query cache.

  35. 35. How do you make an optimistic update with SWR's mutate?

    Correct answer: Pass optimisticData and rollbackOnError

    mutate(updateTodo(newTodo), { optimisticData: [...todos, newTodo], rollbackOnError: true, populateCache: true, revalidate: false }) shows the change immediately and reverts it if the request fails.

  36. 36. What does useSWRMutation give compared to calling fetch and then mutate?

    Correct answer: A trigger function with state tied to a key

    const { trigger, isMutating } = useSWRMutation('/api/todos', sendRequest) - the request runs only when trigger is called, and the key's cache can be updated with the result. It's SWR's counterpart of useMutation.

  37. 37. How does SWR avoid re-rendering a component when unrelated fields of the response change?

    Correct answer: Dependency collection: only fields it reads count

    If a component uses only data, changes to isValidating don't re-render it. SWR also deep-compares data by default (compare option), so an identical refetch doesn't trigger an update.

  38. 38. How do you pass server-fetched data to SWR so the first client render has it?

    Correct answer: As fallback in <SWRConfig>, by the same key

    <SWRConfig value={{ fallback: { '/api/user': user } }}> makes useSWR('/api/user') return data immediately; SWR still revalidates according to its options.

  39. 39. SWR vs TanStack Query: what's a fair summary?

    Correct answer: SWR is simpler; TanStack Query has more features

    Both implement stale-while-revalidate with deduplication and focus revalidation. TanStack Query has richer mutation lifecycles, query cancellation, infinite queries and official devtools; SWR wins on size and simplicity.

  40. 40. Why are route loaders said to remove "request waterfalls" compared with useEffect fetching?

    Correct answer: The router starts all matched loaders in parallel

    With effects a parent renders, then fetches, then renders a child that fetches again. Nested route loaders for /users/:id/orders run concurrently on navigation, and code-split route modules can load in parallel with data.

  41. 41. How do you prevent a loader from re-running after every action on the page?

    Correct answer: Export shouldRevalidate from the route

    By default all active loaders revalidate after an action, which is safe but can be wasteful. shouldRevalidate({ formAction, currentUrl, nextUrl, defaultShouldRevalidate }) lets you opt out selectively.

  42. 42. How do you build optimistic UI with a React Router fetcher?

    Correct answer: Render from fetcher.formData while it's pending

    The submitted values are available immediately: const done = fetcher.formData ? fetcher.formData.get('done') === 'true' : todo.done. After the action completes and loaders revalidate, the real data takes over.

  43. 43. How do you stream slow, non-critical data from a React Router loader?

    Correct answer: Return an unawaited promise and use <Await>

    Await critical data, return the rest as a promise: return { product: await getProduct(), reviews: getReviews() }. The page renders immediately and reviews stream in.

  44. 44. Do you still need a client cache library (TanStack Query) with React Router loaders?

    Correct answer: Often not, though a cache helps with shared data

    Loaders tie data to routes and revalidate after actions. For data used across many routes, background refetching, infinite lists or offline, teams combine them: loaders call queryClient.ensureQueryData, components use useQuery.

  45. 45. How should validation errors from a React Router action reach the form?

    Correct answer: Return them as data, read with useActionData

    Expected errors (an invalid email) are data: return { errors } (often with a 400 status). Thrown errors go to the ErrorBoundary and replace the route UI - that's for unexpected failures.

  46. 46. A legacy app keeps API responses in Redux slices with hand-written loading flags. What's a pragmatic migration?

    Correct answer: Move server data to RTK Query, endpoint by endpoint

    Incremental migration lowers risk: each endpoint replaces a thunk, its slice fields and loading flags. RTK Query lives in the same store, so the two approaches coexist during the transition.

  47. 47. How do you keep two browser tabs' client state in sync (e.g. logout in one tab)?

    Correct answer: With BroadcastChannel or the storage event

    Each tab is a separate JS realm with its own store. A message on logout lets other tabs clear their state; persist storage events can rehydrate Zustand. Server caches also refetch on focus.

  48. 48. What's the main risk of copying server data from useQuery into a Zustand/Redux store?

    Correct answer: Two sources of truth: the copy goes stale

    Read server data from the query cache wherever needed (the same hook in many components is deduplicated). Store only client decisions (selected id, filters) and derive the rest.

  49. 49. Which approach makes state logic easiest to unit-test regardless of the library?

    Correct answer: Keep transitions in pure functions

    A reducer or a store action can be tested by calling it with an input and asserting the output. Components are then tested for behavior (React Testing Library), with server calls mocked at the network layer (e.g. MSW).

  50. 50. When is a finite state machine (e.g. XState) a better model than a reducer with flags?

    Correct answer: For complex flows with guarded transitions

    Flags like isLoading/isError/isSuccess allow impossible combinations. A machine (or a reducer over a discriminated union) makes states explicit and transitions guarded; statecharts add nesting and parallel states.

  51. 51. How do you push WebSocket updates into an RTK Query cache entry?

    async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) {
      await cacheDataLoaded;
      const ws = new WebSocket(url);
      ws.onmessage = (e) => updateCachedData((draft) => { draft.push(JSON.parse(e.data)); });
      await cacheEntryRemoved;
      ws.close();
    }

    Correct answer: With onCacheEntryAdded and updateCachedData

    The socket lives exactly as long as some component subscribes to that cache entry, and updates go through Immer drafts like other cache updates.

  52. 52. How do you implement infinite scrolling with a single RTK Query cache entry?

    Correct answer: With serializeQueryArgs, merge and forceRefetch

    By default each argument (page) gets its own cache entry. These options combine them into one growing list; newer RTK versions also offer infinite query endpoints.

  53. 53. What does persisting the TanStack Query cache (persistQueryClient) give you, and what must you watch out for?

    Correct answer: Instant data after reload; bust it on version changes

    Persisted queries older than their gcTime are discarded, and a buster string invalidates storage when the data shape changes. Never persist sensitive data unencrypted.

  54. 54. What happens to TanStack Query requests when the browser goes offline (default networkMode: 'online')?

    Correct answer: They pause and resume when the connection returns

    The onlineManager tracks connectivity. networkMode: 'offlineFirst' tries the request once (e.g. for service-worker caches); 'always' ignores connectivity.

  55. 55. What is wrong with this cache update?

    queryClient.setQueryData(["todos"], (old) => {
      old.push(newTodo);
      return old;
    });

    Correct answer: It mutates the cached data instead of copying it

    Write (old) => old ? [...old, newTodo] : [newTodo]. Cached data is treated as immutable, just like React state.

  56. 56. How should components using TanStack Query be set up in tests?

    Correct answer: A fresh QueryClient per test, with retry: false

    A shared client leaks cache between tests; retries make failing requests take seconds. Mock the network (MSW) rather than the hook.

  57. 57. How do you give each instance of a complex widget its own Zustand store?

    const StoreContext = createContext(null);
    function Editor({ initial }) {
      const [store] = useState(() => createStore(() => ({ ...initial })));
      return <StoreContext value={store}>...</StoreContext>;
    }

    Correct answer: Create a vanilla store per instance and pass it via Context

    This also allows initializing from props. Creating the store in a useState initializer keeps it stable across renders.

  58. 58. How do you react to very frequent Zustand changes (e.g. pointer position at 60fps) without re-rendering?

    Correct answer: Use store.subscribe and update a ref directly

    Re-rendering React components at that rate is expensive. Writing to a ref or style directly keeps the store as the source of truth without render cost.

  59. 59. What is an efficient way to implement undo/redo for a large document state?

    Correct answer: Record patches or keep a bounded history

    Structural sharing makes snapshots cheap, and patches are compact enough to sync or persist. Cap the history and group rapid changes into one step.

  60. 60. Why validate state read from the URL (search params) with a schema?

    const filters = FiltersSchema.parse(Object.fromEntries(searchParams));

    Correct answer: URLs are user-controlled input

    A schema (e.g. Zod) coerces strings to numbers, applies defaults and rejects garbage. Treat the URL like any external API.

  61. 61. Why send an idempotency key with an optimistic "create order" request that may be retried?

    Correct answer: So retries of it don't create duplicates

    Retries after timeouts are common with automatic retry logic. Generating the key on the client also lets the optimistic item and the server item share an id.

  62. 62. How do you show a global indicator for all in-flight React Router fetchers (e.g. several "like" buttons)?

    Correct answer: Read them with useFetchers() and check their states

    useFetchers also enables optimistic UI from anywhere, e.g. a list reflecting pending deletions triggered from detail panels.

  63. 63. What does SWR's custom cache provider option allow?

    Correct answer: Replacing the default in-memory Map

    Wrap tests in <SWRConfig value={{ provider: () => new Map() }}> so each test starts with an empty cache.

  64. 64. With React Server Components fetching data on the server, what typically changes about client-side state libraries?

    Correct answer: Read-only server data often needs no client cache

    Pages can render with data directly from the server. TanStack Query and similar still shine for infinite lists, polling, optimistic updates and cross-route caching.

  65. 65. Why does React Redux implement useSelector on top of useSyncExternalStoreWithSelector?

    Correct answer: To subscribe safely in concurrent rendering

    The selector runs on every store change, and the result is compared (by === or a custom equality) before React schedules a render.

  66. 66. How should independently deployed micro-frontends share state like the current user?

    Correct answer: Through a small explicit contract, like events

    Coupling to another team's internal store breaks on their next refactor. Keep shared state minimal and versioned like any API.

  67. 67. When does useSelector(selector, shallowEqual) help?

    const { name, email } = useSelector((s) => ({ name: s.user.name, email: s.user.email }), shallowEqual);

    Correct answer: When a new object often has equal fields

    Without it, the new object fails === and re-renders on every action. Alternatives: select primitives separately or use a memoized selector.

  68. 68. Which approach suits collaborative editing where several users change the same document offline and online?

    Correct answer: CRDT-based state, like Yjs or Automerge

    CRDTs guarantee all replicas converge after exchanging updates. They add memory overhead and need a sync layer, but avoid manual conflict resolution.

  69. 69. How do you update an edited todo in every cached list (filtered views) at once?

    queryClient.setQueriesData({ queryKey: ["todos", "list"] }, (old) =>
      old?.map((t) => (t.id === updated.id ? updated : t)));

    Correct answer: Use setQueriesData with a key prefix

    setQueriesData applies the updater to every matching query. Invalidating is simpler when list membership might change (e.g. completed todos leave a filter).

  70. 70. Why can dependent queries create a waterfall, and how do you reduce it?

    Correct answer: Each waits for the previous; fetch on the server

    Client-side chains add a full round-trip per step. Loaders, server components or a backend-for-frontend endpoint collapse them.

  71. 71. How does staleTime: Infinity differ from refetchOnMount: false?

    Correct answer: staleTime: Infinity stops all automatic triggers

    With refetchOnMount: false, focus and reconnect still refetch stale data. Fresh data can still be invalidated explicitly.

  72. 72. When is an event bus better than shared state for cross-feature communication?

    Correct answer: For one-off notifications nobody reads later

    Storing transient events in state leads to flags that must be reset. Events decouple producers and consumers; persistent facts belong in state.

  73. 73. Why model async state as a discriminated union instead of separate fields?

    type State =
      | { status: "idle" }
      | { status: "loading" }
      | { status: "success"; data: User[] }
      | { status: "error"; error: string };

    Correct answer: Impossible combinations can't be represented

    Libraries like TanStack Query expose the same idea via status. In your own reducers it removes defensive checks throughout the UI.

  74. 74. What's wrong with providesTags: (result) => result.map(({ id }) => ({ type: "Post", id }))?

    Correct answer: On a failed query, result is undefined

    Write result ? [...result.map(...), { type: "Post", id: "LIST" }] : [{ type: "Post", id: "LIST" }] so a later mutation can still trigger a refetch after an error.

  75. 75. Where should an unsaved long form draft live so it survives a reload or crash?

    Correct answer: In localStorage or IndexedDB

    In-memory stores vanish on reload. Debouncing avoids writing on every keystroke; versioning the stored shape prevents restoring incompatible drafts.