devsetswww.devsets.com/en/topics/state-management/notes
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
useStatenext 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, notset_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
childrenfirst. - Context.
- Passes a value down the tree without props:
createContext, a provider,useContextoruse. Best for rarely changing data: theme, locale, current user. - Re-renders.
- Every consumer renders when the provider's
valuechanges, andReact.memodoesn't stop it. Memoize the value and split state anddispatchinto separate contexts. - Custom hook.
useAuth()hidesuseContext(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
useStateoruseReducer. 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 wrapschildrenin 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
useAppSelectoranduseAppDispatchonce. - Selectors.
- A selector that returns a new object or array re-renders the component on every action. Memoize it with
createSelectoror select primitives. - createAsyncThunk.
- Wraps an async request and dispatches
pending,fulfilledandrejected; they are handled inextraReducers. - Normalized state.
{ ids, entities }instead of nested arrays: fast lookup by id and one place to update.createEntityAdaptergenerates 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.
createreturns 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, useuseShallow.- 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(),setStateandsubscribework in API helpers, tests and analytics without a component.- Middleware.
persistsaves tolocalStorage(withpartializeandversionfor migrations),devtoolsconnects 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.
queryKeyidentifies data in the cache,queryFnloads it. Every variable thequeryFnuses must be in the key. The app is wrapped inQueryClientProvider.- 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.
isPendingmeans there's no data yet,isFetchingmeans any request is running, including a background refetch.- Mutations.
useMutationsends changes; after success,invalidateQueries({ queryKey: ["todos"] })refetches all keys starting withtodos.- Default behavior.
- Refetches on window focus and reconnect, retries a failed query 3 times, and deduplicates identical requests.
- Useful options.
enabledfor dependent queries,placeholderData: keepPreviousDatafor pagination,selectto 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.
createApiwithbuilder.queryandbuilder.mutationgenerates hooks likeuseGetPostsQueryanduseAddPostMutation. Lives in the Redux store.- Tags.
- Queries declare
providesTags, mutationsinvalidatesTags; matching queries refetch. Tags with anidrefetch only the affected entries. - Cache in RTK Query.
- Identical requests are deduplicated, unused data is removed after 60 seconds (
keepUnusedDataFor).skiporskipTokenwaits for an argument. - SWR.
useSWR(key, fetcher): stale-while-revalidate, shows cached data and refetches it. Revalidates on focus and reconnect; anullkey 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
replaceso 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
loaderloads data before the route renders, the component reads it withuseLoaderData. This removes request waterfalls in components. - Actions.
- An
actionhandles a form submission; afterwards the page's loaders revalidate automatically.useFetchersubmits without navigation,useNavigationshows 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.
getSnapshotmust 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
QueryClientper request, otherwise data leaks between users. Prefetched data is passed to the client throughdehydrateandHydrationBoundary. - 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
QueryClientwithretry: falsein every test. - Tab sync.
BroadcastChannelor thestorageevent syncs logout and settings between browser tabs.
Common pitfalls
- Copying data from
useQueryinto Redux or Zustand: two sources of truth that drift apart. - Storing derived values like
cartTotalorfullNamein 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
useShalloworcreateSelector. - One big Context with a frequently changing value re-renders all consumers, and
React.memodoesn't help. - Mutating state directly outside Immer (
items.push(x); setItems(items)) doesn't cause a render. - A
queryKeywithout all the variables thequeryFnuses shows stale data for other parameters. - A global
QueryClientor 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.okturns an HTTP error into successful data.