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
- 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.
- Start local. Lift state to the closest common parent when siblings need it. Reach for Context or a store only when drilling gets painful.
- Context is dependency injection, not a state manager. Every consumer re-renders when the Provider
valuechanges byObject.is, andReact.memodoes not stop that. - 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.
- 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. - 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. - Middleware signature:
store => next => action => {}. It wrapsdispatchlike an onion. Thunk lets you dispatch functions for async work; saga uses generators and is rarely needed now. createAsyncThunkdispatchespending,fulfilledandrejectedactions. RTK Query goes further: caching, dedupe and tag-based invalidation with auto-generated hooks.- Selectors read and derive state. Reselect's
createSelectormemoizes so the same inputs return the same reference, which avoids pointless re-renders. - Normalize relational data:
{ ids: [], entities: { [id]: item } }, refer to other entities by id. One copy of each item, O(1) lookups, simple updates. - Zustand: a hook-based store with no Provider. Select narrow slices (
useStore(s => s.bears)); useuseShallowwhen you return an object or array. - 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.
- MobX and signals are fine-grained reactive: reads are tracked automatically and only dependents update. Great performance, but more “magic” than explicit dispatch.
- Server state is a cache, not app state. Use TanStack Query or SWR for fetching, caching, dedupe, retries, background refetch and invalidation.
- 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. - 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
useStateoruseReducer. - 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
useStateis 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
childrenor 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 withuseContextor React 19'suse(Context). - React compares the new
valuewith the old one usingObject.is. If it differs, every component that reads that context re-renders. React.memoon 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 inuseMemo. - 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.memostop 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
dispatchan action, a plain object with atype(and usually apayload). - 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 ES2023toSorted,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.nextpasses 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 inconfigureStore. - redux-saga: generator functions that
takeactions and yield effects (call,put,fork,takeLatest). Powerful for complex flows (cancellation, races) but heavy and harder to learn. - Listener middleware (
createListenerMiddlewarein 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
nextanddispatchinside 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.
configureStorecombines 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
undefinedmeans “use the draft”. extraReducerslets 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,combineSlicesfor 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
reducersandextraReducersin 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) => ...)dispatchespending, thenfulfilledorrejected. Handle them inextraReducers.thunkAPIgivesdispatch,getState,signal(AbortSignal),rejectWithValueand more. Theconditionoption 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 likeuseGetPostsQueryanduseAddPostMutation. - 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, mutationsinvalidatesTags, 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. useSelectorre-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,mapor build objects return a new reference every time. Wrap them withcreateSelector. 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
weakMapMemoizeby 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: {...} } }.idskeeps order;entitiesgives O(1) lookup. - Relations are stored as ids (
authorId), not nested objects. Join them in selectors. - Updates become shallow and local: change
entities.u1once and every view that uses it sees the change. - RTK's
createEntityAdaptergives this shape plus reducers (addOne,upsertMany,removeOne,updateOne) and selectors (selectAll,selectById). Thenormalizrlibrary 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
idsandentities? - 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 viauseStore.getState().setmerges 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
useShallowfromzustand/react/shallow. - Middleware:
persist,devtools,immer,subscribeWithSelector,combine. A vanilla store (createStorefromzustand/vanilla) works without React. - Zustand v5 needs React 18+ and uses
useSyncExternalStoreunder the hood.
Interview questions
- Why choose Zustand over Redux?
- How does Zustand avoid unnecessary re-renders?
- Does Zustand
setmerge 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 likeatomWithStorageandatomFamily. - 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 inactions, derive withcomputed, react withautorun/reaction.makeAutoObservable(this)sets this up for a class. - Wrap React components in
observer(frommobx-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 anawait, wrap updates inrunInAction. - 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'srefworks 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
cacheTimebefore 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
refetchIntervalpolling. - 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:
statusis'pending' | 'error' | 'success'(data),fetchStatusis'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
isPendingmean versusisFetching?
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 withgetQueryData,setQueryDatawith the guess, and return the snapshot as context. - In
onError, restore the snapshot. InonSettled, invalidate so the cache matches the server whatever happened. - Simpler v5 option: render the pending
variablesfromuseMutationin the UI whileisPending, 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; passnullto 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 globalmutate(key)to revalidate;mutate(key, data, { optimisticData, rollbackOnError })for optimistic UI;useSWRMutationfor remote mutations. - Extras:
useSWRInfinitefor pagination,SWRConfigfor 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
useStatefirst, 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 (
partializein Zustand,whitelistin 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, JotaiatomWithStorage, redux-persist, and TanStack'spersistQueryClientfor an offline-ready server cache. - Sync across tabs with the
storageevent orBroadcastChannel.
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
dispatchand 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: falseso tests are isolated and failures show quickly. - Zustand: reset the store between tests (save the initial state and
setState(initial, true)inafterEach). Jotai: wrap each test in its ownProvider.
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/useShallowfor 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, anduseTransition/useDeferredValueto 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?