Overview
Curated: · Written: · Reviewed:
React state management
The interview question is not 'Redux or Zustand'. It is 'who owns this value, how long does it live, and who is allowed to write it.' A candidate who answers with a library name is answering a question nobody asked. A candidate who answers with ownership, lifetime, and update frequency is answering the one that decides the architecture.
The mental model: state management is a decision about ownership and lifetime, not about storage location. Every tool in the React ecosystem (useState, lifting, Context, Redux, Zustand, TanStack Query) is a different answer to 'who owns this, and how does a change reach the components that care.' Pick the tool after you have answered that.
Why state management is the interview question
A small React app can keep everything in one component and work fine. A large one cannot, and the failure does not arrive gradually. It shows up as a specific class of bug that reviewers recognize quickly:
- A value is duplicated in two places and the copies drift. The cart total says $42, the checkout says $40.
- A
useEffectrefetches on every mount, so navigating back and forth fires four requests, and whichever response arrives last wins even if it is not the current one. - A Context provider passes an inline object, so every consumer re-renders on every keystroke in an unrelated input.
- A selector returns a fresh object on each call, so
useSelectorre-renders on every dispatch, and someone 'fixes' it by addinguseMemoin the wrong place.
Each of these is a state-ownership mistake with a library attached. Interviewers use this topic because it separates people who have debugged a real app from people who have only read the docs. The questions are about re-render traces, cache invalidation, and where a value should live, and the good answers come from having been wrong about them before.
What gets probed: can you name the lowest common owner of a piece of state, can you predict what re-renders when it changes, do you separate server data from client data, and can you say when a library is not worth its cost.
The mental model: ownership, not location
Location is where the value is stored. Ownership is which component is allowed to change it. Lifting state moves ownership up the tree. Context changes the read path without changing ownership: the provider still owns the setter. That distinction is the core of the topic.
Four questions settle almost every case:
- What is the lowest common ancestor that needs to read it? That component owns the value. If the answer is one component, it is local state and you are finished.
- How long does it live? A form input lives until submit. A logged-in user lives for the session. A fetched list lives until it goes stale. Lifetime determines whether the value belongs in a component, a store, or a cache.
- How often does it change, and how many components read it? High frequency combined with wide readership is the case that breaks Context and justifies an external store with selector subscriptions.
- Who is the source of truth? If the server owns the value, you are not managing state. You are managing a cache of someone else's state, which is a different problem with different tools.
A corollary: derived values are not state. const total = items.reduce(...) computed during render is correct. A useState plus a useEffect that recomputes total whenever items changes is a bug generator: it renders twice, and it can show a stale total between the two renders.
Local state, lifting, and composition before Context
react.dev's Managing State chapter walks this ladder in order: react to input, choose the state structure, share state between components, preserve and reset state, extract logic into a reducer, pass data deeply with context, scale up with reducer and context. Climb to the next rung only when the current one causes trouble.
Local state. useState for a value that one component reads and writes. Use useReducer when updates form a state machine: several fields that must change together, or transitions you want to name.
Lifting. Two siblings need the same value, so you move it to their parent and pass the value and setter down. This is the correct answer more often than candidates expect. It makes the owner obvious and keeps data flow one-directional.
Composition. Before lifting data through three layers, check whether you can pass JSX instead. A Layout that renders {children} never needs to know about user:
// Drilling: Layout takes user only to hand it to Avatar
<Layout user={user} />
// Composition: Layout is unaware of user
<Layout><Avatar user={user} /></Layout>
That single move removes a large share of the prop drilling people reach for Context to solve.
State structure rules that reviewers check: no redundant state (compute it), no duplicated state (one owner), no contradictory state (a pair of booleans that can both be true is a bug), no deeply nested state (normalize it), and no state that mirrors a prop (it will desync on the next prop change).
Context: what it re-renders and what it is not for
Context is dependency injection for a value. createContext creates the channel, <Provider value={...}> publishes, and useContext subscribes. React 19 adds use(Context), which can be called conditionally and inside loops, unlike useContext.
The re-render rule is exact: every consumer of a context re-renders when the provider's value changes by Object.is. A provider re-render by itself does not re-render consumers if the value is referentially stable.
Trace of the most common Context bug, with three consumers under one provider:
function App() {
const [user, setUser] = useState(null);
const [query, setQuery] = useState('');
// New object on every App render, so Object.is fails for every consumer
return (
<AuthContext.Provider value={{ user, setUser }}>
<SearchInput value={query} onChange={setQuery} />
<Header />
<Sidebar />
</AuthContext.Provider>
);
}
Each keystroke calls setQuery, which re-renders App. The inline object is new, so Header and Sidebar re-render even though neither reads query. React.memo on those children does not prevent it, because the update arrives through context rather than props.
Two standard fixes. Memoize the value: const value = useMemo(() => ({ user, setUser }), [user]). Or split the channel so the setter, which never changes, lives in its own context. React's useReducer guide does this with separate StateContext and DispatchContext providers.
Two things Context is not:
- It is not a store. It has no selectors, middleware, devtools, or time travel. Context plus
useReduceris a small Redux, and a reasonable one until you need any of those. - It is not for high-frequency updates. A context carrying mouse position, scroll offset, or a live text field re-renders every consumer on every event. This is the misconception interviewers test for.
Do not use Context for a value read by a single subtree that you could pass as a prop, for a value that changes every frame, or for a large object graph where consumers need different slices.
Redux and Redux Toolkit: store, slices, selectors, middleware
Redux keeps one store holding the whole client state tree. Components dispatch plain action objects, pure reducers compute the next state, and subscribers are notified. Because reducers are pure and actions are serializable, you get time-travel debugging, action logs, and replayable state. Those features are what justify the ceremony.
Redux Toolkit (RTK) is the current way to write it. configureStore sets up redux-thunk, the Redux DevTools integration, and development-only immutability and serializability checks by default. createSlice takes a name, an initial state, and a reducers object, and generates the action creators and action types. Immer is bundled, so reducers can be written in a mutating style and still produce immutable updates:
const cartSlice = createSlice({
name: 'cart',
initialState: { items: [], coupon: null },
reducers: {
itemAdded(state, action) { state.items.push(action.payload); }, // Immer drafts this
couponApplied(state, action) { state.coupon = action.payload; },
},
});
export const { itemAdded, couponApplied } = cartSlice.actions;
Selectors decide re-render cost. useSelector re-renders when the selected value changes by reference, so returning a new object on each call re-renders on every dispatch:
// Re-renders on every dispatch: new object identity on each call
const { a, b } = useSelector(s => ({ a: s.a, b: s.b }));
// Fixed: shallow comparison of the result
const { a, b } = useSelector(s => ({ a: s.a, b: s.b }), shallowEqual);
// Fixed: memoized selector that recomputes only when a or b changes
const selectAB = createSelector([s => s.a, s => s.b], (a, b) => ({ a, b }));
Reselect's createSelector memoizes on input identity, so the result is recomputed only when a or b actually changes. Side effects belong in middleware: createAsyncThunk for request lifecycles, createListenerMiddleware for reacting to actions, and RTK Query for data fetching.
Redux earns its cost when many independent parts of the app write the same state, when update logic is complex, when you need an audit trail or time travel, when a large team benefits from enforced conventions, or when non-React code must read and dispatch. It does not earn its cost for a theme toggle.
Zustand and the lightweight external store
Zustand is a store that lives outside React and is subscribed to through a hook. There is no provider, no action types, and no reducers. A create call returns a hook:
import { create } from 'zustand';
const useCart = create((set) => ({
items: [],
addItem: (item) => set((s) => ({ items: [...s.items, item] })),
clear: () => set({ items: [] }),
}));
// Subscribes to one derived value; re-renders only when that value changes
const count = useCart((s) => s.items.length);
Zustand subscribes through useSyncExternalStore, the React 18 API built for this job. It keeps concurrent rendering from showing two components different versions of the same store, which is the tearing problem. Any hand-written external store should use it too.
Compared with Redux, Zustand gives you less convention: nothing stops a teammate from putting a fetch inside a setter. It has no built-in time travel, and devtools are opt-in through middleware. In return you get a much smaller surface and no provider nesting. Middleware covers the common needs: persist for localStorage, immer for draft-style updates, devtools, and subscribeWithSelector for imperative subscriptions outside React.
The selector trap applies here too. const { a, b } = useCart() subscribes to the whole store and re-renders on any change. Use atomic selectors, or useShallow for multi-field reads. For large stores, split the store into named slices composed inside create.
Zustand v5 requires React 18 or later. Jotai and Valtio are in the same weight class with different models, atomic bottom-up state and proxy-based mutable state respectively. Name them as alternatives, not as defaults.
Server state vs client state: different tools
Server state is asynchronous, shared with other users, owned by a backend you do not control, and stale the moment you receive it. Client state is synchronous, local, and authoritative. They fail differently, so they need different tools.
The hand-rolled cache is the pattern interviewers ask you to critique:
useEffect(() => {
let alive = true;
fetch(`/api/user/${id}`).then(r => r.json()).then(d => alive && setUser(d));
return () => { alive = false; };
}, [id]);
The alive flag discards responses from a previous id, so it does handle out-of-order results. What it lacks is deduplication (two components mounting together fire two requests), caching (every mount refetches), background revalidation, retry with backoff, and invalidation after a mutation. You end up rebuilding a cache, usually badly.
TanStack Query, SWR, and RTK Query replace this pattern. Their defaults differ in ways that matter:
| TanStack Query v5 | RTK Query | |
|---|---|---|
| Stale time | staleTime: 0 | Not a separate concept; data is refetched on subscription |
| Cache retention | gcTime: 5 min | keepUnusedDataFor: 60 s |
| Refetch on window focus | true | false |
| Refetch on reconnect | true | false |
| Retries | 3, exponential backoff capped at 30 s | none by default |
TanStack Query v5 renamed cacheTime to gcTime. A candidate who still says cacheTime learned the API before late 2023. The shift in thinking is that server data stops living in Redux and sits in a cache keyed by query. You invalidate with invalidateQueries after mutations and use optimistic updates where latency is visible.
Choosing: a decision table
| Situation | Tool | Why |
|---|---|---|
| One component reads and writes it | useState / useReducer | The lowest owner is the component itself |
| Two siblings need it | Lift to parent | Owner is explicit; no new dependency |
| Deep tree, read-mostly, low churn (theme, locale, current user) | Context | Cheap, built in, no library |
| Same, but updates at frame rate | External store or CSS variables | Context re-renders every consumer per update |
| Many writers, complex transitions, audit or time travel | Redux Toolkit | Conventions and devtools justify the ceremony |
| Small global client state, no provider wanted | Zustand | Small core, selector subscriptions |
| Anything fetched over HTTP | TanStack Query / RTK Query / SWR | Caching, deduplication, revalidation are the job |
| Derived from props or state | Compute during render | No state, no sync bug |
| Form input | Local state, or a form library | Lifetime is the form |
Bundle cost, approximate min+gzip and version-dependent: Zustand's core is around 1 kB. Redux Toolkit with React-Redux lands around 15 to 20 kB. The difference is real but rarely decisive, since a single date library can outweigh it. The decisive costs are conceptual. Redux asks every contributor to learn actions, reducers, and selectors. Zustand asks for discipline it does not enforce.
Failure modes that show up in review
- Global state for everything. A modal's open flag in Redux because Redux is available. Every global value is a value any component can now change, which is usually the opposite of what you want.
- Derived state in
useState. Two sources of truth that drift. Compute the value. - Inline Context value. Covered above. It is the most common re-render bug in React codebases.
- Selector returning a new object.
useSelector(s => ({...})), oruseStore()with no selector. Re-renders on every dispatch or every store change. - Server data in the client store. You now own invalidation, deduplication, and staleness by hand. Use a query library.
useEffectas a state synchronizer. Effects that copy props into state, or state into other state. Each creates a render where the two disagree.- Mutating state directly.
state.items.push(x)outside an Immer draft does not notify Redux subscribers, and inuseStateit does not trigger a render. - Stale closures in subscriptions. An effect that captures a value and never re-subscribes keeps reading the old value.
- Context as a store. Without selectors, every consumer re-renders on any change to the value.
What changes at scale: SSR, bundle size, testing, migration
SSR and hydration. A module-level store is shared across requests on the server. A Zustand create at module scope can leak one user's state into another user's response under concurrent SSR. The fix is a store factory with one provider per request. Redux has the same constraint: create the store inside the request handler, never at module scope. TanStack Query can dehydrate the cache on the server and hydrate it on the client, so the first paint has data without a refetch.
Bundle size. The bigger lever at scale is code-splitting the store. RTK's combineSlices and Zustand's slices pattern both let you register reducers lazily alongside the route that needs them.
Testing. Redux's store is plain JavaScript, so reducers and selectors test without React. For components, a common pattern is a renderWithProviders helper that wraps Provider and a fresh QueryClient per test, with retry: false so failures surface immediately. Zustand stores are module singletons, so reset them between tests with store.setState(initialState, true) or export a factory.
Migration. RTK's configureStore accepts the existing reducer, so an old createStore app can migrate one slice at a time. RTK Query replaces hand-written thunks incrementally. Moving from Context to Zustand is a provider swap plus selector rewrites. The migration that goes badly is the one done for its own sake. If the current tool is not causing a named problem, the rewrite is risk with no payoff.
React Compiler (1.0, October 2025) auto-memoizes components and hooks, which removes some manual memo and useMemo work. It does not change where state lives or how Context propagates, so the decisions above stand.
Interview signals: what a strong answer sounds like
A strong answer starts with ownership and lifetime, names the lowest common owner, and only then names a tool. It separates server state from client state without being prompted. It can trace a re-render: 'this provider value is a new object on each render, so all four consumers re-render on every keystroke; memoizing the value or splitting the dispatch context fixes it.' It knows Context's cost and says when not to use it. It can cite a concrete default (staleTime: 0, gcTime of 5 minutes, RTK Query's keepUnusedDataFor of 60 seconds) and explain what changes when you tune it. It names the migration path and the reason to take it.
A weak answer names a library in the first sentence and defends it. It says 'Context is for global state' without mentioning re-renders. It stores fetched data in Redux and calls that state management. It cannot say what re-renders when a value changes, or it claims React.memo stops context updates. It treats 'we use Redux' as an architecture instead of a trade-off.
The follow-up that separates the two: 'You have a theme value read by 200 components and a live cursor position read by 3. Same tool?' The answer is no, and the reason is the re-render rule, not the library's feature list.