State Management 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. What will count be after one click if it starts at 0?

    function handleClick() {
      setCount(count + 1);
      setCount((c) => c + 1);
      setCount(count + 1);
    }

    Correct answer: 1

    Updates are queued in order: count + 1 = 1 (snapshot 0), then c => c + 1 = 2, then count + 1 = 1 again - the last update replaces the value with 1. Mixing snapshot values with updaters gives surprising results; prefer updaters when depending on the previous value.

  2. 2. How do you reset a form component's state when the selected user changes?

    Correct answer: Render it with key={userId} so React recreates the component

    A different key makes React treat it as a new component: old state is dropped and the initial values apply. A resetting effect first renders stale data and then fixes it - an extra render and a visible flash.

  3. 3. Why can storing a copy of a prop in state be a bug?

    function Message({ color }) {
      const [c, setC] = useState(color);
      return <p style={{ color: c }}>Hi</p>;
    }

    Correct answer: The value is used once; later changes are ignored

    "Mirroring" props in state freezes the first value. If the component should follow the prop, use it directly. Copy into state only when you intentionally need an initial value (and name it initialColor).

  4. 4. How do you pass dispatch from useReducer deep into the tree without prop drilling?

    Correct answer: Put dispatch into its own context

    The "reducer + context" pattern: one context for state, another for dispatch. Components that only send actions (buttons, forms) read the stable dispatch context and don't re-render when the state changes.

  5. 5. What's the purpose of the third argument init in useReducer(reducer, arg, init)?

    Correct answer: Lazy initialization on the first render

    useReducer(reducer, username, createInitialState) avoids recomputing an expensive initial state on every render - like a lazy initializer in useState. init can also be reused to reset the state.

  6. 6. 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 each time, and React compares it with Object.is

    A new object literal is never equal to the previous one. Memoize: const value = useMemo(() => ({ user, login, logout }), [user, login, logout]) with useCallback for the functions (the React Compiler can do this automatically).

  7. 7. A component uses only theme from a big AppContext but re-renders on every cart update. What helps?

    Correct answer: Split the context into smaller ones by domain and change frequency

    React.memo doesn't stop re-renders caused by a context the component reads. Separate ThemeContext and CartContext limit updates to the consumers that need them. For very frequent updates, use a store with selectors.

  8. 8. Why doesn't React.memo help a component that calls useContext(CartContext)?

    Correct answer: Memo compares props, but context bypasses them

    Context updates bypass the props comparison. A workaround: read the context in a small parent and pass only the needed value to a memoized child, so the child skips rendering when that value is unchanged.

  9. 9. Is Context a state management library?

    Correct answer: No: it's a dependency injection mechanism

    Context only transports a value through the tree. It has no selectors, middleware, devtools or caching. Combined with useReducer it covers many apps, but for frequent updates and fine-grained subscriptions a store is better.

  10. 10. What happens with nested providers of the same context?

    <ThemeContext value="dark">
      <Sidebar />
      <ThemeContext value="light">
        <Panel />
      </ThemeContext>
    </ThemeContext>

    Correct answer: Panel reads "light" - the nearest provider wins

    useContext looks up to the closest provider. Overriding a value for a subtree is a legitimate pattern: a dark section inside a light page, a nested form with its own settings.

  11. 11. When is it better to put a value in Context instead of passing it explicitly through props?

    Correct answer: When many components at different depths need it and it rarely changes

    Context trades explicitness for convenience: it's harder to see where data comes from, and components depend on a provider being present. Use it for truly cross-cutting values; otherwise explicit props or composition are clearer.

  12. 12. What's wrong with this case reducer?

    todoAdded(state, action) {
      state.items.push(action.payload);
      return { ...state, count: state.count + 1 };
    }

    Correct answer: You can't both mutate the Immer draft and return a new value

    Either mutate the draft (state.items.push(...); state.count += 1) or return a completely new state - Immer throws if you do both.

  13. 13. Which actions does createAsyncThunk('users/fetch', fn) dispatch?

    Correct answer: pending, then fulfilled or rejected

    Reducers handle them in extraReducers via builder.addCase(fetchUsers.fulfilled, ...) to set loading flags, data and errors. For cached server data RTK Query removes most of this code.

  14. 14. Why does this selector re-render the component on every dispatched action?

    const done = useSelector((s) => s.todos.filter((t) => t.done));

    Correct answer: filter returns a new array every time

    useSelector reruns after every dispatch and compares results with ===. Use a memoized selector from createSelector, which returns the same array as long as s.todos hasn't changed.

  15. 15. What is extraReducers in createSlice for?

    Correct answer: Handling actions defined outside this slice (thunks, other slices)

    reducers creates the slice's own actions, while extraReducers reacts to external ones: builder.addCase(fetchUser.fulfilled, ...) or builder.addCase(logout, () => initialState).

  16. 16. How do you type useSelector and useDispatch in a TypeScript project?

    Correct answer: Infer RootState and create typed hooks

    type RootState = ReturnType<typeof store.getState>, type AppDispatch = typeof store.dispatch, then useSelector.withTypes<RootState>(). Types follow the reducers automatically.

  17. 17. What does normalized state ({ ids, entities }) give you?

    Correct answer: Each item is stored once, by its id

    Nested duplicated data goes out of sync (the same user in a list and in comments). createEntityAdapter provides normalized state plus addOne, upsertMany, removeOne and selectors like selectAll/selectById.

  18. 18. What does configureStore check in development mode?

    Correct answer: State mutations and non-serializable values

    The immutability and serializability middleware catch bugs early: a mutation outside Immer or a Date/class instance/promise in the store. They're removed in production builds.

  19. 19. Should form input state (each keystroke) go into Redux?

    Correct answer: Usually not: keep it local and dispatch the result on submit

    The Redux style guide recommends deciding per piece of state. Ephemeral UI state (typing, hover, an open dropdown) is local; the store holds data shared across the app or that must survive navigation.

  20. 20. Why does this component re-render on every store change?

    const { count, inc } = useStore();

    Correct answer: Without a selector it subscribes to the whole store

    useStore() returns the whole state object, so any change re-renders the component. Select what you need: useStore((s) => s.count) and useStore((s) => s.inc).

  21. 21. Why does a selector returning a new object cause extra re-renders (or a loop in v5)?

    const { a, b } = useStore((s) => ({ a: s.a, b: s.b }));

    Correct answer: The object is new each time; use useShallow

    Zustand compares selector results with Object.is. useShallow((s) => ({ a: s.a, b: s.b })) compares the fields shallowly and keeps the same reference if they're equal.

  22. 22. How do you read or update a Zustand store outside React components (e.g. in an API helper)?

    Correct answer: With useStore.getState() and useStore.setState()

    The hook returned by create also carries the vanilla store API: getState, setState, subscribe. Handy for interceptors, websockets and tests.

  23. 23. How does set in Zustand handle nested objects?

    set({ user: { name: "Ann" } }); // state was { user: { name, email }, theme }

    Correct answer: It merges only one level deep

    set does a shallow merge of the top level. For nested updates spread explicitly: set((s) => ({ user: { ...s.user, name: 'Ann' } })), or use the immer middleware.

  24. 24. How is a large Zustand store usually organized?

    Correct answer: Into slices combined in one create

    The slices pattern: createBearSlice, createFishSlice get set/get and return their part; create((...a) => ({ ...createBearSlice(...a), ...createFishSlice(...a) })). Separate stores per domain are also fine.

  25. 25. Why can a persist-ed store cause a hydration mismatch in SSR apps?

    Correct answer: Server defaults differ from the client's stored values

    The server has no localStorage, so its HTML uses initial values. Wait for hydration (persist.hasHydrated()/onFinishHydration) before showing persisted values, or render them only on the client.

  26. 26. How does staleTime differ from gcTime?

    Correct answer: staleTime is freshness; gcTime is memory lifetime

    Fresh data isn't refetched on mount or focus. Stale data is still shown from cache and refreshed in the background. gcTime (formerly cacheTime, 5 minutes by default) starts when the query has no observers.

  27. 27. How does isPending differ from isFetching?

    Correct answer: isPending: no data; isFetching: any request

    Show a skeleton when isPending, and a subtle indicator when isFetching while old data is visible. In v4 the first was called isLoading.

  28. 28. How do you refresh the list after useMutation creates an item?

    Correct answer: Call invalidateQueries in onSuccess

    Invalidation marks matching queries stale and refetches active ones. Alternatively write the returned object into the cache with setQueryData. Hooks can't be called inside callbacks.

  29. 29. Which queries does invalidateQueries({ queryKey: ['todos'] }) match?

    Correct answer: Every query whose key starts with ['todos']

    Prefix matching makes hierarchical keys useful: ['todos'] → ['todos', 'list', filters] → ['todos', 'detail', id]. Use exact: true for an exact match.

  30. 30. How do you run a query only after another one returned user.id?

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

    While enabled is false the query doesn't run. Calling hooks conditionally breaks the rules of hooks. user.id must also be part of the dependent query's key.

  31. 31. With pagination, how do you keep showing the previous page while the next one loads?

    Correct answer: placeholderData: keepPreviousData

    A new key (['projects', page]) starts with an empty cache. placeholderData shows the previous data meanwhile, and isPlaceholderData lets you disable the "Next" button.

  32. 32. What does TanStack Query do on a failed query by default?

    Correct answer: Retries 3 times with exponential backoff

    retry: 3 with a growing retryDelay. Mutations aren't retried by default. You can skip retries for 4xx: retry: (count, err) => err.status >= 500 && count < 3.

  33. 33. Why should every variable the queryFn uses be part of the queryKey?

    Correct answer: Otherwise different data shares one cache key

    The key is the cache identity, like effect dependencies. useQuery({ queryKey: ['todos'], queryFn: () => fetchTodos(filter) }) shows the old filter's results. The ESLint plugin exhaustive-deps for queries catches this.

  34. 34. How do you make an RTK Query mutation refetch the post list?

    getPosts: build.query({ query: () => "posts", providesTags: ["Post"] }),
    addPost: build.mutation({ query: (body) => ({ url: "posts", method: "POST", body }) }),

    Correct answer: Add invalidatesTags: ['Post'] to addPost

    Tags link the cache to mutations. For finer control, tag items by id ({ type: 'Post', id }) plus a 'LIST' tag, so editing one post refetches only what's affected.

  35. 35. When does RTK Query remove unused data from its cache?

    Correct answer: After keepUnusedDataFor seconds without subscribers

    RTK Query counts hook subscriptions per endpoint and argument. If something subscribes again within that time, data comes from the cache. The TanStack Query counterpart is gcTime.

  36. 36. How do you skip an RTK Query request until an argument is available?

    Correct answer: Pass skip: !id or the skipToken instead of the argument

    useGetUserQuery(id ?? skipToken) keeps the hook call unconditional while preventing the request. It's the counterpart of enabled: false in TanStack Query.

  37. 37. How does RTK Query avoid duplicate requests when 3 components call useGetUserQuery(1)?

    Correct answer: Requests with the same endpoint and argument are deduplicated into one

    The cache key is endpoint + serialized argument. All subscribers share one request and one cache entry, which also stays alive while any of them is mounted.

  38. 38. What does the refetchOnMountOrArgChange option do in RTK Query?

    Correct answer: Forces a refetch on mount or argument change

    By default RTK Query serves cached data to new subscribers. refetchOnMountOrArgChange: true (or a number of seconds) refetches if the data is older than that. Related options: refetchOnFocus, refetchOnReconnect, pollingInterval.

  39. 39. When does SWR revalidate data automatically by default?

    Correct answer: On mount, on window focus and on network reconnect

    Each trigger can be turned off (revalidateOnFocus: false, revalidateOnReconnect: false), and polling is enabled with refreshInterval. For immutable data there's useSWRImmutable.

  40. 40. How do you fetch data in SWR only when a condition is met?

    const { data } = useSWR(userId ? `/api/user/${userId}` : null, fetcher);

    Correct answer: Pass null as the key

    A null key means "don't fetch". The key can also be a function that throws or returns a falsy value while a dependency is missing - that's how dependent requests are built.

  41. 41. What does mutate(key) from useSWRConfig do?

    Correct answer: Revalidates the cached data for that key

    After a POST you call mutate('/api/todos') so every component using that key refetches. You can also pass new data to update the cache immediately, and the bound mutate from useSWR updates its own key.

  42. 42. Why do two components with the same SWR key make only one request?

    Correct answer: SWR deduplicates requests with the same key within dedupingInterval

    Within the deduping interval (2 seconds by default) concurrent requests for one key are merged, and both components share the cached data. That lets you call useUser() in many components freely.

  43. 43. How do you set a default fetcher and options for all SWR hooks?

    Correct answer: Wrap the app in <SWRConfig value={{ fetcher, ... }}>

    SWRConfig sets global options (fetcher, revalidateOnFocus, error handlers) and can be nested to override them for a subtree. It can also provide initial fallback data from SSR.

  44. 44. How does a component read the data returned by its route loader?

    Correct answer: With useLoaderData() (or the loaderData prop in framework mode)

    The router runs the loader before rendering the route and passes the result in. With type generation in framework mode, loaderData is fully typed.

  45. 45. What happens after a React Router action completes?

    Correct answer: The router revalidates the page's loaders

    Automatic revalidation after mutations is the core idea: the URL and loaders are the source of truth for server data, so no client cache synchronization code is needed.

  46. 46. How do you show a pending state during navigation or form submission in React Router?

    Correct answer: Read useNavigation().state

    navigation.state !== 'idle' means the router is loading a page or submitting a form, and navigation.formData holds the submitted data - enough for spinners and disabled buttons.

  47. 47. When should you use useFetcher instead of <Form>?

    Correct answer: To call a loader or action without navigating

    A fetcher has its own state (fetcher.state, fetcher.data) and doesn't change the URL, so many independent mutations can run on one page (a todo list, inline edits).

  48. 48. How do you redirect from an action after creating an item?

    Correct answer: Return (or throw) redirect('/items/' + id) from the action

    Loaders and actions run outside components, so hooks aren't available. redirect creates a response the router follows. Hooks like useNavigate work only in components.

  49. 49. Server data is in TanStack Query. What's usually left for a global client store?

    Correct answer: A little UI state, like theme or open panels

    Once server cache moves to a dedicated tool, the remaining client state is often small. Copying server data into Redux/Zustand recreates the sync problems the query library solves.

  50. 50. How does RTK Query compare to TanStack Query?

    Correct answer: Similar goals, but it lives in the Redux store

    Both cache server data with deduplication, invalidation and optimistic updates. RTK Query uses tags, its cache is visible in Redux DevTools and integrates with slices; TanStack Query has a standalone cache, query keys and a broad feature set (infinite queries, suspense).

  51. 51. What is the prepare callback in a createSlice reducer for?

    todoAdded: {
      reducer(state, action) { state.push(action.payload); },
      prepare(text) { return { payload: { id: nanoid(), text } }; },
    }

    Correct answer: Building the action payload before the reducer

    Reducers must be pure, so random ids or timestamps are created in prepare. Callers still dispatch todoAdded("text").

  52. 52. How do you handle the pending state of many thunks with one case in a slice?

    builder.addMatcher(isPending(fetchUsers, fetchPosts), (state) => { state.loading = true; });

    Correct answer: Use builder.addMatcher with a matcher like isPending(...)

    Matchers run for any action that satisfies them. RTK ships isPending, isFulfilled, isRejected and isAnyOf helpers.

  53. 53. Should you store cartTotal in the Redux state next to items?

    Correct answer: No - derive it with a (memoized) selector from items

    Duplicated derived data drifts out of sync. Keep the minimal state and compute the rest in selectors, as the Redux style guide recommends.

  54. 54. How do you skip a thunk if the data is already loaded or loading?

    createAsyncThunk("users/fetch", fetchUsers, {
      condition: (_, { getState }) => getState().users.status === "idle",
    });

    Correct answer: Use the condition option of the thunk

    When condition returns false, no actions are dispatched. RTK Query handles such deduplication automatically.

  55. 55. How does a component get the thunk's result or catch its error?

    try {
      const user = await dispatch(saveUser(data)).unwrap();
      navigate(`/users/${user.id}`);
    } catch (err) {
      showError(err.message);
    }

    Correct answer: Call .unwrap() on the promise from dispatch

    Without unwrap, the promise always resolves with the final action (fulfilled or rejected), which is easy to mishandle.

  56. 56. How do you add RTK Query endpoints from a lazily loaded feature?

    Correct answer: Call api.injectEndpoints({ endpoints: ... }) in the feature module

    Injecting keeps one API slice and cache while splitting code by feature. The injected hooks are exported from the returned object.

  57. 57. How do you refetch an RTK Query every 30 seconds while the component is mounted?

    Correct answer: useGetStatsQuery(undefined, { pollingInterval: 30_000 })

    Polling stops automatically on unmount. skipPollingIfUnfocused avoids requests in background tabs.

  58. 58. How do you make a component re-render only when one post from a cached list changes?

    const { post } = useGetPostsQuery(undefined, {
      selectFromResult: ({ data }) => ({ post: data?.find((p) => p.id === id) }),
    });

    Correct answer: Use the selectFromResult option

    The hook compares the selected value shallowly and skips re-renders when it is unchanged. Return stable references from the selector.

  59. 59. What does the second argument true do in Zustand's set(newState, true)?

    Correct answer: Replaces the whole state instead of merging

    By default set shallow-merges. Replace mode is useful for resets, but forgetting actions in the new object removes them from the store.

  60. 60. Why do some teams group Zustand actions into a nested actions object?

    const useBearStore = create((set) => ({
      bears: 0,
      actions: { increase: () => set((s) => ({ bears: s.bears + 1 })) },
    }));
    export const useBearActions = () => useBearStore((s) => s.actions);

    Correct answer: Actions never change, so selecting them is safe

    Selecting the stable actions object returns the same reference every time. Exposing custom hooks also hides the store shape from components.

  61. 61. How does initialData differ from placeholderData in TanStack Query?

    Correct answer: initialData counts as real cached data

    Use initialData when you truly have the data (e.g. from a list); use placeholderData for previews or keeping previous data while fetching.

  62. 62. What does the queryOptions helper give you?

    export const todoQuery = (id: number) =>
      queryOptions({ queryKey: ["todo", id], queryFn: () => fetchTodo(id) });
    useQuery(todoQuery(5));
    queryClient.prefetchQuery(todoQuery(5));

    Correct answer: Reusable, type-safe query definitions

    Keys and functions stay together, and queryClient.getQueryData(todoQuery(5).queryKey) gets the right data type automatically.

  63. 63. How do you poll a query every 10 seconds with TanStack Query?

    Correct answer: refetchInterval: 10_000

    staleTime only marks data stale; it doesn't trigger fetches by itself. refetchIntervalInBackground controls polling in hidden tabs.

  64. 64. How does mutateAsync differ from mutate?

    Correct answer: mutateAsync returns a promise you can await

    Use mutate with onSuccess/onError for most UI; use mutateAsync when you need to chain logic, e.g. close a dialog after the save resolves.

  65. 65. How do you fetch a dynamic number of queries in parallel (e.g. one per selected id)?

    const results = useQueries({
      queries: ids.map((id) => ({ queryKey: ["user", id], queryFn: () => getUser(id) })),
    });

    Correct answer: With useQueries

    Calling hooks in a loop breaks the rules of hooks when the length changes. useQueries caches each query separately and has a combine option.

  66. 66. How can you make opening a detail page feel instant?

    <Link to={`/posts/${id}`} onMouseEnter={() => queryClient.prefetchQuery(postQuery(id))}>

    Correct answer: Prefetch the query on hover or focus

    Prefetching respects staleTime, so repeated hovers don't spam the server. Routers with loaders can call ensureQueryData similarly.

  67. 67. Which SWR hook implements "load more" pagination?

    Correct answer: useSWRInfinite

    You provide getKey(pageIndex, previousPageData), and setSize(size + 1) loads the next page. Return null to stop when there are no more pages.

  68. 68. How do you start an SWR request before the component renders (e.g. on hover)?

    Correct answer: Call preload(key, fetcher)

    preload can run outside React (route handlers, hover). Combined with Suspense mode it removes loading waterfalls.

  69. 69. What does keepPreviousData: true do in SWR when the key changes (e.g. a new search query)?

    Correct answer: Keeps showing old data until the new data arrives

    It avoids flashing an empty state while typing. Show a subtle indicator using isLoading/isValidating.

  70. 70. What happens when a React Router loader throws?

    Correct answer: The nearest route ErrorBoundary renders instead of the route component

    Inside the boundary useRouteError() returns the error; isRouteErrorResponse distinguishes thrown responses like 404 from unexpected errors.

  71. 71. What is clientLoader in React Router framework mode?

    Correct answer: A loader that runs in the browser

    It can call the server loader via serverLoader() and add a client cache. With clientLoader.hydrate = true it also runs on initial load.

  72. 72. Why update search params with { replace: true } while the user types a filter?

    setSearchParams({ q: value }, { replace: true });

    Correct answer: To avoid a history entry per keystroke

    Push a new entry only for meaningful navigations (e.g. submitting a search). Debouncing the update reduces loader calls too.

  73. 73. What is the difference between optimistic and pessimistic updates?

    Correct answer: Optimistic updates change the UI before confirmation

    Optimistic UI feels instant for likely-successful actions (likes, toggles). Use pessimistic updates for payments and anything hard to undo.

  74. 74. How can a header badge show all pending "add to cart" mutations from other components?

    const pending = useMutationState({
      filters: { mutationKey: ["addToCart"], status: "pending" },
    });

    Correct answer: With useMutationState, filtering by a shared mutationKey

    It reads the global mutation cache, enabling optimistic UI in places unrelated to the component that triggered the mutation.

  75. 75. How do you integrate a WebSocket price feed into SWR's cache?

    Correct answer: With the useSWRSubscription hook

    Subscriptions are deduplicated by key like normal requests, so several components share one socket subscription.