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.
1. What will
countbe after one click if it starts at 0?function handleClick() { setCount(count + 1); setCount((c) => c + 1); setCount(count + 1); }Correct answer:
1Updates are queued in order:
count + 1= 1 (snapshot 0), thenc => c + 1= 2, thencount + 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. 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 componentA different
keymakes 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. 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. How do you pass
dispatchfromuseReducerdeep into the tree without prop drilling?Correct answer: Put
dispatchinto its own contextThe "reducer + context" pattern: one context for
state, another fordispatch. Components that only send actions (buttons, forms) read the stable dispatch context and don't re-render when the state changes.5. What's the purpose of the third argument
initinuseReducer(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 inuseState.initcan also be reused to reset the state.6. Why do all context consumers re-render on every provider render?
<AuthContext value={{ user, login, logout }}> {children} </AuthContext>Correct answer:
valueis a new object each time, and React compares it withObject.isA new object literal is never equal to the previous one. Memoize:
const value = useMemo(() => ({ user, login, logout }), [user, login, logout])withuseCallbackfor the functions (the React Compiler can do this automatically).7. A component uses only
themefrom a bigAppContextbut re-renders on every cart update. What helps?Correct answer: Split the context into smaller ones by domain and change frequency
React.memodoesn't stop re-renders caused by a context the component reads. SeparateThemeContextandCartContextlimit updates to the consumers that need them. For very frequent updates, use a store with selectors.8. Why doesn't
React.memohelp a component that callsuseContext(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. 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
useReducerit covers many apps, but for frequent updates and fine-grained subscriptions a store is better.10. What happens with nested providers of the same context?
<ThemeContext value="dark"> <Sidebar /> <ThemeContext value="light"> <Panel /> </ThemeContext> </ThemeContext>Correct answer:
Panelreads"light"- the nearest provider winsuseContextlooks 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. 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. 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. Which actions does
createAsyncThunk('users/fetch', fn)dispatch?Correct answer:
pending, thenfulfilledorrejectedReducers handle them in
extraReducersviabuilder.addCase(fetchUsers.fulfilled, ...)to set loading flags, data and errors. For cached server data RTK Query removes most of this code.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:
filterreturns a new array every timeuseSelectorreruns after every dispatch and compares results with===. Use a memoized selector fromcreateSelector, which returns the same array as long ass.todoshasn't changed.15. What is
extraReducersincreateSlicefor?Correct answer: Handling actions defined outside this slice (thunks, other slices)
reducerscreates the slice's own actions, whileextraReducersreacts to external ones:builder.addCase(fetchUser.fulfilled, ...)orbuilder.addCase(logout, () => initialState).16. How do you type
useSelectoranduseDispatchin a TypeScript project?Correct answer: Infer
RootStateand create typed hookstype RootState = ReturnType<typeof store.getState>,type AppDispatch = typeof store.dispatch, thenuseSelector.withTypes<RootState>(). Types follow the reducers automatically.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).
createEntityAdapterprovides normalized state plusaddOne,upsertMany,removeOneand selectors likeselectAll/selectById.18. What does
configureStorecheck 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. 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. 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)anduseStore((s) => s.inc).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
useShallowZustand 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. How do you read or update a Zustand store outside React components (e.g. in an API helper)?
Correct answer: With
useStore.getState()anduseStore.setState()The hook returned by
createalso carries the vanilla store API:getState,setState,subscribe. Handy for interceptors, websockets and tests.23. How does
setin Zustand handle nested objects?set({ user: { name: "Ann" } }); // state was { user: { name, email }, theme }Correct answer: It merges only one level deep
setdoes a shallow merge of the top level. For nested updates spread explicitly:set((s) => ({ user: { ...s.user, name: 'Ann' } })), or use theimmermiddleware.24. How is a large Zustand store usually organized?
Correct answer: Into slices combined in one
createThe slices pattern:
createBearSlice,createFishSlicegetset/getand return their part;create((...a) => ({ ...createBearSlice(...a), ...createFishSlice(...a) })). Separate stores per domain are also fine.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. How does
staleTimediffer fromgcTime?Correct answer:
staleTimeis freshness;gcTimeis memory lifetimeFresh data isn't refetched on mount or focus. Stale data is still shown from cache and refreshed in the background.
gcTime(formerlycacheTime, 5 minutes by default) starts when the query has no observers.27. How does
isPendingdiffer fromisFetching?Correct answer:
isPending: no data;isFetching: any requestShow a skeleton when
isPending, and a subtle indicator whenisFetchingwhile old data is visible. In v4 the first was calledisLoading.28. How do you refresh the list after
useMutationcreates an item?Correct answer: Call
invalidateQueriesinonSuccessInvalidation 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. 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]. Useexact: truefor an exact match.30. How do you run a query only after another one returned
user.id?Correct answer: Pass
enabled: !!user?.idto the dependent queryWhile
enabledis false the query doesn't run. Calling hooks conditionally breaks the rules of hooks.user.idmust also be part of the dependent query's key.31. With pagination, how do you keep showing the previous page while the next one loads?
Correct answer:
placeholderData: keepPreviousDataA new key (
['projects', page]) starts with an empty cache.placeholderDatashows the previous data meanwhile, andisPlaceholderDatalets you disable the "Next" button.32. What does TanStack Query do on a failed query by default?
Correct answer: Retries 3 times with exponential backoff
retry: 3with a growingretryDelay. Mutations aren't retried by default. You can skip retries for 4xx:retry: (count, err) => err.status >= 500 && count < 3.33. Why should every variable the
queryFnuses be part of thequeryKey?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 pluginexhaustive-depsfor queries catches this.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']toaddPostTags 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. When does RTK Query remove unused data from its cache?
Correct answer: After
keepUnusedDataForseconds without subscribersRTK 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. How do you skip an RTK Query request until an argument is available?
Correct answer: Pass
skip: !idor theskipTokeninstead of the argumentuseGetUserQuery(id ?? skipToken)keeps the hook call unconditional while preventing the request. It's the counterpart ofenabled: falsein TanStack Query.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. What does the
refetchOnMountOrArgChangeoption 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. 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 withrefreshInterval. For immutable data there'suseSWRImmutable.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
nullas the keyA
nullkey 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. What does
mutate(key)fromuseSWRConfigdo?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 boundmutatefromuseSWRupdates its own key.42. Why do two components with the same SWR key make only one request?
Correct answer: SWR deduplicates requests with the same key within
dedupingIntervalWithin 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. How do you set a default
fetcherand options for all SWR hooks?Correct answer: Wrap the app in
<SWRConfig value={{ fetcher, ... }}>SWRConfigsets global options (fetcher,revalidateOnFocus, error handlers) and can be nested to override them for a subtree. It can also provide initialfallbackdata from SSR.44. How does a component read the data returned by its route
loader?Correct answer: With
useLoaderData()(or theloaderDataprop in framework mode)The router runs the loader before rendering the route and passes the result in. With type generation in framework mode,
loaderDatais fully typed.45. What happens after a React Router
actioncompletes?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. How do you show a pending state during navigation or form submission in React Router?
Correct answer: Read
useNavigation().statenavigation.state !== 'idle'means the router is loading a page or submitting a form, andnavigation.formDataholds the submitted data - enough for spinners and disabled buttons.47. When should you use
useFetcherinstead 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. How do you redirect from an
actionafter creating an item?Correct answer: Return (or throw)
redirect('/items/' + id)from the actionLoaders and actions run outside components, so hooks aren't available.
redirectcreates a response the router follows. Hooks likeuseNavigatework only in components.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. 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. What is the
preparecallback in acreateSlicereducer 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 dispatchtodoAdded("text").52. How do you handle the
pendingstate of many thunks with one case in a slice?builder.addMatcher(isPending(fetchUsers, fetchPosts), (state) => { state.loading = true; });Correct answer: Use
builder.addMatcherwith a matcher likeisPending(...)Matchers run for any action that satisfies them. RTK ships
isPending,isFulfilled,isRejectedandisAnyOfhelpers.53. Should you store
cartTotalin the Redux state next toitems?Correct answer: No - derive it with a (memoized) selector from
itemsDuplicated derived data drifts out of sync. Keep the minimal state and compute the rest in selectors, as the Redux style guide recommends.
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
conditionoption of the thunkWhen
conditionreturnsfalse, no actions are dispatched. RTK Query handles such deduplication automatically.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 fromdispatchWithout
unwrap, the promise always resolves with the final action (fulfilled or rejected), which is easy to mishandle.56. How do you add RTK Query endpoints from a lazily loaded feature?
Correct answer: Call
api.injectEndpoints({ endpoints: ... })in the feature moduleInjecting keeps one API slice and cache while splitting code by feature. The injected hooks are exported from the returned object.
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.
skipPollingIfUnfocusedavoids requests in background tabs.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
selectFromResultoptionThe hook compares the selected value shallowly and skips re-renders when it is unchanged. Return stable references from the selector.
59. What does the second argument
truedo in Zustand'sset(newState, true)?Correct answer: Replaces the whole state instead of merging
By default
setshallow-merges. Replace mode is useful for resets, but forgetting actions in the new object removes them from the store.60. Why do some teams group Zustand actions into a nested
actionsobject?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
actionsobject returns the same reference every time. Exposing custom hooks also hides the store shape from components.61. How does
initialDatadiffer fromplaceholderDatain TanStack Query?Correct answer:
initialDatacounts as real cached dataUse
initialDatawhen you truly have the data (e.g. from a list); useplaceholderDatafor previews or keeping previous data while fetching.62. What does the
queryOptionshelper 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. How do you poll a query every 10 seconds with TanStack Query?
Correct answer:
refetchInterval: 10_000staleTimeonly marks data stale; it doesn't trigger fetches by itself.refetchIntervalInBackgroundcontrols polling in hidden tabs.64. How does
mutateAsyncdiffer frommutate?Correct answer:
mutateAsyncreturns a promise you can awaitUse
mutatewithonSuccess/onErrorfor most UI; usemutateAsyncwhen you need to chain logic, e.g. close a dialog after the save resolves.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
useQueriesCalling hooks in a loop breaks the rules of hooks when the length changes.
useQueriescaches each query separately and has acombineoption.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 callensureQueryDatasimilarly.67. Which SWR hook implements "load more" pagination?
Correct answer:
useSWRInfiniteYou provide
getKey(pageIndex, previousPageData), andsetSize(size + 1)loads the next page. Returnnullto stop when there are no more pages.68. How do you start an SWR request before the component renders (e.g. on hover)?
Correct answer: Call
preload(key, fetcher)preloadcan run outside React (route handlers, hover). Combined with Suspense mode it removes loading waterfalls.69. What does
keepPreviousData: truedo 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. What happens when a React Router loader throws?
Correct answer: The nearest route
ErrorBoundaryrenders instead of the route componentInside the boundary
useRouteError()returns the error;isRouteErrorResponsedistinguishes thrown responses like 404 from unexpected errors.71. What is
clientLoaderin 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. WithclientLoader.hydrate = trueit also runs on initial load.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. 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. 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 sharedmutationKeyIt reads the global mutation cache, enabling optimistic UI in places unrelated to the component that triggered the mutation.
75. How do you integrate a WebSocket price feed into SWR's cache?
Correct answer: With the
useSWRSubscriptionhookSubscriptions are deduplicated by key like normal requests, so several components share one socket subscription.