PrepStack › Frontend › State Management

State Management interview cheat sheet

Local vs global vs server state, Redux Toolkit, Zustand, atoms, signals and TanStack Query

Interviewers use state management to see if you can put each piece of state in the right place and explain the trade-offs. Expect questions on Context re-renders, Redux principles and Redux Toolkit, selectors and normalization, lighter stores like Zustand and Jotai, and server state with TanStack Query. Many snippets here are tiny dependency-free versions of the real libraries, so you can explain how they work inside. Read the 15-minute revision first, then switch to Quiz mode.

15-minute revision

  1. Five kinds of state: local UI (useState), global client (theme, auth, cart), server (cached API data), URL (filters, page, ids) and form state. Pick the tool per kind, not one tool for all.
  2. Start local. Lift state to the closest common parent when siblings need it. Reach for Context or a store only when drilling gets painful.
  3. Context is dependency injection, not a state manager. Every consumer re-renders when the Provider value changes by Object.is, and React.memo does not stop that.
  4. Redux's three principles: single source of truth, state is read-only (change it only by dispatching actions), and changes are made by pure reducers.
  5. Reducers must be pure and immutable: same input gives the same output, no side effects, and return new objects for changed paths. Mutation breaks === change detection.
  6. Redux Toolkit is the official way to write Redux: configureStore (thunk, DevTools, dev checks), createSlice (actions plus reducer) and Immer so you can write “mutating” code safely.
  7. Middleware signature: store => next => action => {}. It wraps dispatch like an onion. Thunk lets you dispatch functions for async work; saga uses generators and is rarely needed now.
  8. createAsyncThunk dispatches pending, fulfilled and rejected actions. RTK Query goes further: caching, dedupe and tag-based invalidation with auto-generated hooks.
  9. Selectors read and derive state. Reselect's createSelector memoizes so the same inputs return the same reference, which avoids pointless re-renders.
  10. Normalize relational data: { ids: [], entities: { [id]: item } }, refer to other entities by id. One copy of each item, O(1) lookups, simple updates.
  11. Zustand: a hook-based store with no Provider. Select narrow slices (useStore(s => s.bears)); use useShallow when you return an object or array.
  12. Atoms (Jotai, Recoil) build state bottom-up: small atoms plus derived atoms, and only components that read an atom re-render. Recoil is archived; use Jotai.
  13. MobX and signals are fine-grained reactive: reads are tracked automatically and only dependents update. Great performance, but more “magic” than explicit dispatch.
  14. Server state is a cache, not app state. Use TanStack Query or SWR for fetching, caching, dedupe, retries, background refetch and invalidation.
  15. TanStack Query v5 defaults: staleTime: 0 (data is stale at once), gcTime: 5 min (unused cache is deleted), retry: 3, refetch on mount, window focus and reconnect.
  16. Optimistic update recipe: cancel queries, snapshot old data, write new data, roll back on error, invalidate on settle.

Foundations: where state lives

Kinds of state

Classify state first: local, global client, server, URL or form. Each has a natural home.

  • Local UI state belongs to one component or a small subtree: open/closed, hover, input text. Use useState or useReducer.
  • Global client state is owned by the browser and needed in many places: theme, logged-in user, cart, feature flags. Use Context, Zustand, Redux or atoms.
  • Server state lives on the server; the client only holds a cache that can go stale. It needs fetching, caching, dedupe and invalidation, so use TanStack Query, SWR or RTK Query.
  • URL state: filters, search, sort, page, selected tab or id. Put it in the path or query string so it survives refresh and can be shared and bookmarked.
  • Form state: values, touched, dirty and errors. Libraries like React Hook Form keep inputs uncontrolled for speed; plain useState is fine for small forms.
  • Derived state should be computed during render (or memoized), not stored. Storing it creates two sources of truth that can drift.

Interview questions

  • What kinds of state exist in a frontend app?
  • What is the difference between client state and server state?
  • When would you put state in the URL?
  • Why is storing derived state a bad idea?

Lifting state & prop drilling

Move shared state to the closest common parent. Pass it down. Fix deep drilling with composition before reaching for Context.

  • Lifting state up: when two siblings need the same data, move it to their nearest common parent and pass the value and a setter down as props.
  • This keeps a single source of truth and one-way data flow: data goes down, events go up through callbacks.
  • Prop drilling is passing props through components that do not use them, just to reach a deep child. A few levels is fine and explicit.
  • First fix: component composition. Pass children or elements as props so the middle layers never see the data.
  • When many distant components need it, use Context or a store. Also consider colocation: move state down to where it is actually used.

Interview questions

  • What does “lifting state up” mean?
  • What is prop drilling and how do you avoid it?
  • Is prop drilling always bad?

Context API & its re-render pitfalls

Context passes a value deep without props. Every consumer re-renders when that value changes, so split and memoize it.

  • Create with createContext(default), provide with a Provider (in React 19 you can render <ThemeContext value={...}> directly), read with useContext or React 19's use(Context).
  • React compares the new value with the old one using Object.is. If it differs, every component that reads that context re-renders.
  • React.memo on a consumer does not block a context update. Memo only skips re-renders caused by the parent.
  • Pitfall 1: value={{ user, setUser }} creates a new object on every render of the provider, so all consumers re-render each time. Wrap it in useMemo.
  • Pitfall 2: one big context. A change to any field re-renders every consumer. Split contexts by concern, or split state and dispatch into two contexts.
  • Context has no selectors: a component cannot subscribe to only part of the value. For frequent, fine-grained updates use a store with selectors (Zustand, Redux, Jotai).

Interview questions

  • Is Context a state management tool?
  • Why do all consumers re-render when one field in the context changes?
  • Will React.memo stop a context consumer from re-rendering?
  • Context vs Redux: when do you pick which?

Flux, Redux & Redux Toolkit

Flux & Redux principles

One store, read-only state, changes only through actions handled by pure reducers. Data flows one way.

  • Flux (Facebook, 2014) introduced one-way data flow: View → Action → Dispatcher → Store → View. Redux simplified it to one store and no dispatcher.
  • Single source of truth: the whole app's global state is one object tree in one store.
  • State is read-only: the only way to change it is to dispatch an action, a plain object with a type (and usually a payload).
  • Pure reducers compute the next state: (state, action) => newState. No side effects, no randomness, no mutation.
  • The store API is tiny: getState(), dispatch(action), subscribe(listener). Everything else (React bindings, async, devtools) is built on top.
  • Benefits: predictable updates, easy logging, time-travel debugging, simple testing. Cost: more boilerplate (mostly removed by Redux Toolkit).

Interview questions

  • What are the three principles of Redux?
  • Explain the Redux data flow.
  • Difference between Flux and Redux?
  • Why must reducers be pure?

Reducers & immutable updates

Copy every level on the path you change and reuse untouched branches. Mutation hides changes from === checks.

  • Redux, React and memoized selectors detect changes with reference equality (===). If you mutate, the reference stays the same and nothing updates.
  • Immutable update = copy along the path: new root, new parent, new changed object. Everything else keeps its old reference (structural sharing).
  • Tools: object spread {...obj}, array spread, map, filter, concat, slice, and ES2023 toSorted, toReversed, toSpliced, with.
  • Mutating methods to avoid on state: push, pop, splice, sort, reverse, direct assignment, delete.
  • Spread is shallow. Nested data needs a spread at every level, which is why Immer (used by Redux Toolkit) is popular.

Interview questions

  • Why does Redux require immutable updates?
  • What is structural sharing?
  • How do you update a deeply nested value immutably?

Middleware: thunk, saga & listeners

Middleware wraps dispatch to add logging, async logic and side effects. Thunk is the default; sagas are rarely needed today.

  • Signature: storeAPI => next => action => result. next passes the action on to the next middleware, and finally to the reducer.
  • Middlewares are composed like an onion: the first one listed runs first on the way in and last on the way out.
  • redux-thunk: if the action is a function, call it with (dispatch, getState) instead of passing it on. That is how you do async work. It is included by default in configureStore.
  • redux-saga: generator functions that take actions and yield effects (call, put, fork, takeLatest). Powerful for complex flows (cancellation, races) but heavy and harder to learn.
  • Listener middleware (createListenerMiddleware in RTK) is the modern lightweight alternative to sagas and observables for “when action X happens, run this effect”.
  • Other uses: logging, crash reporting, analytics, persistence, auth token refresh.

Interview questions

  • What is Redux middleware and what is its signature?
  • How does redux-thunk work?
  • Thunk vs saga: which would you choose?
  • What is the difference between next and dispatch inside a middleware?

Redux Toolkit: configureStore, createSlice, Immer

RTK is the official, standard way to write Redux. It removes boilerplate and makes immutable updates safe with Immer.

  • configureStore combines slice reducers, adds thunk, enables Redux DevTools, and in development adds immutability and serializability check middleware.
  • createSlice({ name, initialState, reducers }) generates action creators and action types ('todos/added') plus the reducer from one object.
  • Reducers in a slice use Immer: you “mutate” a draft, and Immer produces a new immutable state with structural sharing.
  • Immer rule: either mutate the draft or return a new value, never both in the same reducer. Returning undefined means “use the draft”.
  • extraReducers lets a slice respond to actions defined elsewhere (thunks, other slices). In RTK 2.0 only the builder callback form is allowed.
  • Other tools: createEntityAdapter (normalized CRUD), createSelector (re-exported Reselect), createListenerMiddleware, combineSlices for lazy-loaded slices.

Interview questions

  • What is Redux Toolkit and why is it recommended?
  • How can you “mutate” state in createSlice if Redux needs immutability?
  • What is the difference between reducers and extraReducers in createSlice?
  • What happens if you both mutate the draft and return a new object?

createAsyncThunk & RTK Query

createAsyncThunk standardizes loading/success/error actions. RTK Query removes hand-written fetching state entirely.

  • createAsyncThunk('users/fetch', async (arg, thunkAPI) => ...) dispatches pending, then fulfilled or rejected. Handle them in extraReducers.
  • thunkAPI gives dispatch, getState, signal (AbortSignal), rejectWithValue and more. The condition option can skip the request (for example, already loading).
  • dispatch(thunk()).unwrap() returns a promise that resolves with the payload or throws the error, handy in components.
  • RTK Query (createApi + fetchBaseQuery) defines endpoints and auto-generates hooks like useGetPostsQuery and useAddPostMutation.
  • It caches per endpoint and argument, dedupes identical requests, keeps unused data for keepUnusedDataFor (default 60 seconds), and supports polling and refetch on focus/reconnect.
  • Tags link queries and mutations: queries providesTags, mutations invalidatesTags, and matching queries refetch automatically.

Interview questions

  • What actions does createAsyncThunk dispatch?
  • Why use RTK Query instead of thunks for data fetching?
  • How does tag invalidation work in RTK Query?
  • How do you cancel a createAsyncThunk request?

Selectors & Reselect memoization

Selectors encapsulate reads. Memoized selectors return the same reference for the same inputs, so components do not re-render for nothing.

  • A selector is a function state => value. It hides the state shape, so you can refactor the store without touching components.
  • useSelector re-runs after every dispatch and compares the result with the previous one using === by default. A new array or object means a re-render.
  • Selectors that call filter, map or build objects return a new reference every time. Wrap them with createSelector.
  • createSelector(inputSelectors, resultFn): input selectors pull raw values; if they are all === to last time, the cached result is returned.
  • Reselect 5 (bundled with RTK 2) uses weakMapMemoize by default, which caches results for many argument combinations, not just the last one.
  • Keep input selectors simple (no transformation), or memoization never hits. Selectors with parameters can take extra args: selectByCategory(state, 'books').

Interview questions

  • What is a selector and why use one?
  • Why would useSelector(s => s.todos.filter(t => t.done)) cause extra re-renders?
  • How does Reselect decide whether to recompute?
  • useSelector with an object result: what are the options?

Normalized state

Store each entity once in a lookup table by id and reference it by id elsewhere, like a small database.

  • Nested API data often duplicates entities (the same author on many posts). Updating one copy leaves the others stale.
  • Normalized shape per entity type: { ids: ['p1','p2'], entities: { p1: {...}, p2: {...} } }. ids keeps order; entities gives O(1) lookup.
  • Relations are stored as ids (authorId), not nested objects. Join them in selectors.
  • Updates become shallow and local: change entities.u1 once and every view that uses it sees the change.
  • RTK's createEntityAdapter gives this shape plus reducers (addOne, upsertMany, removeOne, updateOne) and selectors (selectAll, selectById). The normalizr library can flatten nested responses.
  • Server-cache libraries (TanStack Query, RTK Query) usually store responses per query instead, so normalization matters most for client-side Redux state.

Interview questions

  • What is state normalization and why do it?
  • Why keep both ids and entities?
  • How would you model posts with comments and authors in Redux?

Lightweight & reactive stores

Zustand

A tiny hook-based store with no Provider. Components subscribe to slices through selectors.

  • create((set, get) => ({ ...state, ...actions })) returns a hook. The store lives outside React, so there is no Provider and it can be used outside components via useStore.getState().
  • set merges the top level by default (set(partial)), but nested objects must still be updated immutably. set(fn) receives the current state.
  • Components select what they need: useStore(s => s.bears) re-renders only when that value changes (Object.is).
  • Returning a new object or array from a selector re-renders every time (in v5 it can even cause an infinite loop). Use useShallow from zustand/react/shallow.
  • Middleware: persist, devtools, immer, subscribeWithSelector, combine. A vanilla store (createStore from zustand/vanilla) works without React.
  • Zustand v5 needs React 18+ and uses useSyncExternalStore under the hood.

Interview questions

  • Why choose Zustand over Redux?
  • How does Zustand avoid unnecessary re-renders?
  • Does Zustand set merge deeply?

Atomic state: Jotai & Recoil

State is split into tiny atoms; derived atoms compute from others. Components re-render only for atoms they read.

  • An atom is a small unit of state. Components read and write it like useState, but it is shared: const [count, setCount] = useAtom(countAtom).
  • Derived atoms compute from other atoms (atom(get => get(a) * 2)) and update automatically. The dependency graph is tracked for you.
  • This is bottom-up: you compose small atoms rather than carving one big store into slices. It suits highly interactive UIs (editors, dashboards) with many independent pieces.
  • Jotai: minimal API (atom, useAtom, useAtomValue, useSetAtom), works without a Provider, supports async atoms with Suspense, and utils like atomWithStorage and atomFamily.
  • Recoil (Meta) introduced atoms and selectors with string keys, but it was archived in 2025 and is not maintained. Recommend Jotai for new code.

Interview questions

  • What is atomic state management?
  • Jotai vs Zustand?
  • Would you choose Recoil for a new project?

MobX & signals: fine-grained reactivity

Reads are tracked automatically. When an observable changes, only the computations that read it re-run.

  • MobX: make state observable, change it in actions, derive with computed, react with autorun/reaction. makeAutoObservable(this) sets this up for a class.
  • Wrap React components in observer (from mobx-react-lite); they re-render only when observables they actually read during render change.
  • MobX lets you mutate directly (this.todos.push(t)); it tracks the change itself. After an await, wrap updates in runInAction.
  • Signals are the same idea at a smaller scale: a value container whose readers are tracked. Used by SolidJS, Preact Signals, Angular (signal, computed, effect), and Svelte 5 runes. Vue's ref works similarly.
  • Signals can update the exact DOM node that depends on them without re-rendering the whole component. React itself does not use signals; it re-renders components.
  • A TC39 proposal to standardize signals in JavaScript exists but is still at an early stage, so do not treat it as a language feature yet.

Interview questions

  • How does MobX know which components to re-render?
  • What are signals and how are they different from React state?
  • Redux vs MobX?

Server state: TanStack Query & SWR

TanStack Query: caching, staleTime vs gcTime

A cache keyed by query keys. staleTime decides when to refetch; gcTime decides when unused data is deleted.

  • useQuery({ queryKey: ['todos', filter], queryFn }) (v5 accepts only the object form). The query key is an array that uniquely identifies the data; include every variable the fetch uses.
  • staleTime (default 0): how long data counts as fresh. Fresh data is served from cache with no request. Stale data is still shown, but refetched in the background on triggers.
  • gcTime (default 5 minutes, called cacheTime before v5): how long an unused query (no mounted observers) stays in memory before it is garbage collected.
  • Refetch triggers for stale queries: new component mounts, window focus, network reconnect, and optional refetchInterval polling.
  • Failed queries retry 3 times with exponential backoff. Identical concurrent requests are deduplicated. Results are structurally shared, so unchanged data keeps its references.
  • v5 status: status is 'pending' | 'error' | 'success' (data), fetchStatus is 'fetching' | 'paused' | 'idle' (network). isLoading = isPending && isFetching.

Interview questions

  • What is the difference between staleTime and gcTime?
  • Why do we need a library like TanStack Query instead of useEffect + fetch?
  • What is a query key and why include variables in it?
  • What does isPending mean versus isFetching?

Mutations, invalidation & optimistic updates

After a write, invalidate related queries. For instant UI, update the cache first and roll back if the server fails.

  • useMutation({ mutationFn, onMutate, onError, onSuccess, onSettled }). Mutations are not cached or retried by default.
  • Invalidation: queryClient.invalidateQueries({ queryKey: ['todos'] }) marks every query whose key starts with ['todos'] as stale and refetches the active ones.
  • Direct cache write: setQueryData(key, updater) when the server returns the new object, saving a round trip. The updater must be immutable.
  • Optimistic update via cache: in onMutate, cancelQueries (so an in-flight refetch does not overwrite you), snapshot with getQueryData, setQueryData with the guess, and return the snapshot as context.
  • In onError, restore the snapshot. In onSettled, invalidate so the cache matches the server whatever happened.
  • Simpler v5 option: render the pending variables from useMutation in the UI while isPending, without touching the cache.

Interview questions

  • How do you keep lists up to date after a mutation?
  • Walk me through an optimistic update.
  • Why call cancelQueries in onMutate?
  • What are the risks of optimistic updates?

SWR & choosing a server-state library

SWR (Vercel) is a smaller stale-while-revalidate hook library. TanStack Query has more features; RTK Query fits Redux apps.

  • Name comes from HTTP stale-while-revalidate: return cached (stale) data immediately, then revalidate in the background and update.
  • const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher). The key is a string or array; pass null to skip fetching (dependent queries).
  • Defaults: revalidate on mount, focus and reconnect; dedupe identical requests within dedupingInterval (2 seconds); retry on error.
  • Writes: bound mutate() or global mutate(key) to revalidate; mutate(key, data, { optimisticData, rollbackOnError }) for optimistic UI; useSWRMutation for remote mutations.
  • Extras: useSWRInfinite for pagination, SWRConfig for global options and fallback data in SSR.

Interview questions

  • What does stale-while-revalidate mean?
  • SWR vs TanStack Query?
  • How do you do dependent queries in SWR and TanStack Query?

Architecture: choosing, persistence, testing, performance

Choosing a solution

Split server state from client state first. Then pick the smallest tool that fits the client state that is left.

  • Step 1: move server data into TanStack Query, SWR or RTK Query. In many apps very little global client state remains.
  • Step 2: keep URL state in the router and form state in a form library or local state.
  • Step 3: for what is left: local useState first, Context for rarely changing app-wide values, Zustand or Jotai for shared frequently changing state, Redux Toolkit for large teams and complex logic.
  • Consider team size, need for DevTools and conventions, SSR, bundle size, and how much logic lives on the client (offline, editors, complex workflows).
  • Mixing is normal: TanStack Query for server data + Zustand for UI state is a very common modern stack.

Interview questions

  • How do you decide where a piece of state should live?
  • Do you still need Redux in 2025?
  • Design question: what state setup would you use for an e-commerce site?
  • Zustand vs Context for global state?

Persisting state

Save a chosen subset to storage, version it, and hydrate carefully. Never persist secrets or server cache by default.

  • Storage choices: localStorage (sync, strings only, about 5 MB per origin), sessionStorage (per tab), IndexedDB (async, large, structured), cookies (sent to server, small).
  • Persist only what you need with a whitelist (partialize in Zustand, whitelist in redux-persist). Skip loading flags, errors and derived data.
  • Add a version and a migrate function so old saved shapes do not crash a new release.
  • Hydration: restoring saved state on startup. With SSR the server has no access to localStorage, so render a default first and hydrate on the client to avoid mismatches.
  • Libraries: Zustand persist, Jotai atomWithStorage, redux-persist, and TanStack's persistQueryClient for an offline-ready server cache.
  • Sync across tabs with the storage event or BroadcastChannel.

Interview questions

  • How would you persist a Redux or Zustand store?
  • What problems does persistence cause with SSR?
  • What should you not persist?

Testing state logic

Unit-test reducers and selectors as pure functions. Test components with a real store and a mocked network.

  • Reducers and selectors are pure: give input, assert output. Freeze inputs to catch accidental mutation.
  • Thunks: call them with a fake dispatch and fake API, then assert the dispatched actions. Or run them against a real store and assert the final state.
  • The Redux docs recommend integration tests: render components with a real store (renderWithProviders) and mock HTTP with MSW, then assert what the user sees.
  • TanStack Query: create a new QueryClient per test with retry: false so tests are isolated and failures show quickly.
  • Zustand: reset the store between tests (save the initial state and setState(initial, true) in afterEach). Jotai: wrap each test in its own Provider.

Interview questions

  • How do you test a reducer?
  • How do you test components connected to Redux or TanStack Query?

Performance & re-render control

Subscribe to as little as possible, keep references stable, and keep fast-changing state close to where it is used.

  • Colocate state: state that changes on every keystroke should live in the smallest component, not a global store.
  • Narrow subscriptions: select primitives or memoized values; use shallowEqual / useShallow for small objects; never subscribe to the whole store.
  • Stable references: memoize Provider values, selectors and callbacks. Normalized state and structural sharing keep untouched branches ===.
  • Split contexts and stores by update frequency (theme vs live cursor position).
  • For heavy renders caused by state changes: React.memo, useMemo, virtualized lists, and useTransition / useDeferredValue to keep typing responsive.
  • The React Compiler (stable since late 2025) auto-memoizes components and values, which reduces manual useMemo/useCallback, but it does not fix over-broad subscriptions.

Interview questions

  • A component re-renders on every store update even though its data did not change. How do you debug it?
  • How do you render a list of 10,000 items from a store efficiently?
  • What is tearing and how do external stores avoid it?
  • Does the React Compiler make state libraries unnecessary?