State Management quick reference for interviews

The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.

Kinds of state

Local UI state.
An open dropdown, an input value, the current tab. Lives in useState next to where it's used.
Global client state.
Theme, the current user, a cart, settings shared by distant parts of the app. Context, Zustand or Redux Toolkit.
Server state.
A copy of data that lives on the server: it can go stale and needs loading, caching and refetching. TanStack Query, RTK Query, SWR or router loaders.
URL state.
Search, filters, sort and page in search params: the page can be shared and survives a reload.
Form state.
Field values and errors are local to the form. React Hook Form, React 19 Actions or plain useState, not a global store.
Derived state.
Whatever can be computed from other state (fullName, cartTotal, a filtered list) is computed during render or in a selector, not stored.

useState and useReducer

Immutable updates.
Create a new object or array: setUser({ ...user, name }). A mutated object with the same reference doesn't trigger a render.
Functional update.
setCount((c) => c + 1) when the next value depends on the previous one, for example several updates in one event.
Lazy initialization.
useState(() => readDraft()) runs the expensive function only on the first render. Changing the argument later doesn't update the state.
Reset with key.
<Profile key={userId} /> remounts the component and resets its state when the user changes.
useReducer.
For state with many transitions. The reducer is a pure function (state, action) => newState, actions are named after events: task_added, not set_tasks.
Colocation.
Keep state as low in the tree as possible and lift it only to the nearest common parent of the components that need it.
function tasksReducer(tasks, action) {
  switch (action.type) {
    case "task_added":
      return [...tasks, action.task];
    case "task_deleted":
      return tasks.filter((t) => t.id !== action.id);
    default:
      throw new Error("Unknown action: " + action.type);
  }
}

const [tasks, dispatch] = useReducer(tasksReducer, []);

Prop drilling and Context

Prop drilling.
Passing props through components that don't use them. Two or three levels is fine; deeper, try composition with children first.
Context.
Passes a value down the tree without props: createContext, a provider, useContext or use. Best for rarely changing data: theme, locale, current user.
Re-renders.
Every consumer renders when the provider's value changes, and React.memo doesn't stop it. Memoize the value and split state and dispatch into separate contexts.
Custom hook.
useAuth() hides useContext(AuthContext) and throws a clear error when the provider is missing.
Not a state manager.
Context only delivers a value; the state itself is still useState or useReducer. It has no selectors, so frequently changing global state fits a store better.
In Next.js.
Providers are client components, so they go into a separate 'use client' file that wraps children in the layout.

Redux Toolkit

configureStore.
Creates the store with DevTools and thunks, and in development checks for state mutations and non-serializable values.
createSlice.
Generates action creators and a reducer from one object. Inside, Immer lets you write state.items.push(x), and an immutable copy is produced.
useSelector and useDispatch.
Read a piece of state and send actions. In TypeScript, create typed useAppSelector and useAppDispatch once.
Selectors.
A selector that returns a new object or array re-renders the component on every action. Memoize it with createSelector or select primitives.
createAsyncThunk.
Wraps an async request and dispatches pending, fulfilled and rejected; they are handled in extraReducers.
Normalized state.
{ ids, entities } instead of nested arrays: fast lookup by id and one place to update. createEntityAdapter generates it.
const cartSlice = createSlice({
  name: "cart",
  initialState: { items: [] as Item[] },
  reducers: {
    itemAdded(state, action: PayloadAction<Item>) {
      state.items.push(action.payload); // Immer
    },
  },
});

export const { itemAdded } = cartSlice.actions;
dispatch(itemAdded(item));

Zustand

Store as a hook.
create returns a hook with state and actions. No provider is needed.
Selectors.
useCart((s) => s.items.length) re-renders only when that value changes. For several fields at once, use useShallow.
set.
Merges the object into the state one level deep. Nested objects are copied by hand. set(state, true) replaces the whole state.
Outside React.
useCart.getState(), setState and subscribe work in API helpers, tests and analytics without a component.
Middleware.
persist saves to localStorage (with partialize and version for migrations), devtools connects Redux DevTools.
SSR.
A module-level store is shared by all requests on the server. In Next.js, create a store per request and pass it through Context.
const useCart = create<CartState>()((set) => ({
  items: [],
  add: (item) =>
    set((s) => ({ items: [...s.items, item] })),
}));

const count = useCart((s) => s.items.length);

TanStack Query

useQuery.
queryKey identifies data in the cache, queryFn loads it. Every variable the queryFn uses must be in the key. The app is wrapped in QueryClientProvider.
staleTime and gcTime.
staleTime (default 0) is how long data counts as fresh without refetching. gcTime (default 5 minutes) is how long unused data stays in the cache.
isPending and isFetching.
isPending means there's no data yet, isFetching means any request is running, including a background refetch.
Mutations.
useMutation sends changes; after success, invalidateQueries({ queryKey: ["todos"] }) refetches all keys starting with todos.
Default behavior.
Refetches on window focus and reconnect, retries a failed query 3 times, and deduplicates identical requests.
Useful options.
enabled for dependent queries, placeholderData: keepPreviousData for pagination, select to transform or pick part of the data.
const { data, isPending } = useQuery({
  queryKey: ["todos", { status }],
  queryFn: () => fetchTodos(status),
  staleTime: 60_000,
});

const qc = useQueryClient();
const add = useMutation({
  mutationFn: createTodo,
  onSuccess: () =>
    qc.invalidateQueries({ queryKey: ["todos"] }),
});

Optimistic updates

Optimistic and pessimistic.
Optimistic shows the change at once and rolls back on error; pessimistic waits for the server response. Optimistic fits likes and toggles, pessimistic fits payments.
Steps.
Cancel queries in flight, save a snapshot, write the new value into the cache, restore the snapshot on error, invalidate at the end.
useOptimistic.
In React 19, shows the expected result while an Action runs and returns to the real value when it finishes.
Idempotency.
A retried request must not create a duplicate: send an idempotency key or a client-generated id.
useMutation({
  mutationFn: updateTodo,
  onMutate: async (todo) => {
    await qc.cancelQueries({ queryKey: ["todos"] });
    const prev = qc.getQueryData(["todos"]);
    qc.setQueryData(["todos"], (old) =>
      old.map((t) => (t.id === todo.id ? todo : t)));
    return { prev };
  },
  onError: (_err, _todo, ctx) =>
    qc.setQueryData(["todos"], ctx.prev),
  onSettled: () =>
    qc.invalidateQueries({ queryKey: ["todos"] }),
});

RTK Query and SWR

RTK Query.
createApi with builder.query and builder.mutation generates hooks like useGetPostsQuery and useAddPostMutation. Lives in the Redux store.
Tags.
Queries declare providesTags, mutations invalidatesTags; matching queries refetch. Tags with an id refetch only the affected entries.
Cache in RTK Query.
Identical requests are deduplicated, unused data is removed after 60 seconds (keepUnusedDataFor). skip or skipToken waits for an argument.
SWR.
useSWR(key, fetcher): stale-while-revalidate, shows cached data and refetches it. Revalidates on focus and reconnect; a null key disables the request.
mutate in SWR.
mutate(key) revalidates a key, mutate(key, data, options) writes data and can do an optimistic update.
Fetcher.
The fetcher must throw on a non-OK HTTP response, otherwise an error page lands in data.

URL and routers

State in the URL.
Search, filters and page go into search params: the link can be shared, and Back works. While typing, update with replace so history doesn't fill up.
Validation.
The URL is user input: parse search params with a schema and fall back to defaults.
React Router loaders.
A loader loads data before the route renders, the component reads it with useLoaderData. This removes request waterfalls in components.
Actions.
An action handles a form submission; afterwards the page's loaders revalidate automatically. useFetcher submits without navigation, useNavigation shows the pending state.
Server Components.
When data is loaded on the server, the client cache is needed only for interactive parts: infinite lists, polling, optimistic updates.

Architecture

useSyncExternalStore.
The hook through which Redux, Zustand and other stores subscribe React to external state without tearing in concurrent rendering. getSnapshot must return the same value while nothing changed.
Choosing tools.
Server data goes to a query library, shared UI state to a small store or Context, the rest stays local. Redux Toolkit pays off in large teams with complex client logic.
SSR.
Create a store and a QueryClient per request, otherwise data leaks between users. Prefetched data is passed to the client through dehydrate and HydrationBoundary.
State machines.
When a reducer grows many boolean flags with impossible combinations, a finite state machine (XState) or a discriminated union { status: "loading" } describes it better.
Testing.
Reducers and selectors are tested as pure functions. For TanStack Query, create a fresh QueryClient with retry: false in every test.
Tab sync.
BroadcastChannel or the storage event syncs logout and settings between browser tabs.

Common pitfalls

  • Copying data from useQuery into Redux or Zustand: two sources of truth that drift apart.
  • Storing derived values like cartTotal or fullName in state: they go out of sync. Compute them.
  • A selector that returns a new object or array re-renders on every change (in Zustand 5 it can even loop). Use useShallow or createSelector.
  • One big Context with a frequently changing value re-renders all consumers, and React.memo doesn't help.
  • Mutating state directly outside Immer (items.push(x); setItems(items)) doesn't cause a render.
  • A queryKey without all the variables the queryFn uses shows stale data for other parameters.
  • A global QueryClient or module-level store on the server shares one user's data with others.
  • Every keystroke of a form in a global store re-renders half the app. Keep form state local.
  • Copying a prop into state: the state doesn't update when the prop changes.
  • A fetcher that doesn't throw on !res.ok turns an HTTP error into successful data.

Cheat sheet