State management in React
Not all state is the same. Local UI state stays in the component, server data belongs in a cache like TanStack Query, filters that people share belong in the URL, and only a small part is real shared client state. If you can sort state into these kinds and pick the right tool for each, you can answer most state management questions in an interview.
Author: bezzad
Contents
The problem: one big store for everything
Our shop keeps everything in one global store: the products, the cart, the user, the open menu, the search text and the filters. Three bug reports came in:
- An admin changed a price. Many users still see the old price until they reload the page.
- A user shares a link to “red shoes under $50”. Their friend opens it and sees all products, without the filters.
- Typing in the search box renders the header, the cart and the footer on every key press.
The store is not the problem. The problem is that four different kinds of state are mixed in one place, and each kind needs a different tool.
Four kinds of state
- Local UI state: is the menu open, the text in an input, the selected tab. Only one component (or a small part of the tree) needs it. Home: useState or useReducer in that component.
- Server state: products, prices, orders. The real copy lives on the server. The browser only has a cached copy that can get old. Home: a server-state cache like TanStack Query, or the loader of your router or framework.
- URL state: the search text, the filters, the page number, the selected product. People want to share, bookmark and go back. Home: the URL (path and search params).
- Shared client state: the cart before checkout, the theme, the signed-in user. It is created in the browser and many distant components read it. Home: context (if it changes rarely) or a small external store.
Ask two questions for every piece of state: “Who owns the real copy?” and “Who needs to read it?” The answers tell you the home.
Local state first
Start with state inside the component. When two siblings need the same state, lift it to their closest common parent and pass it down as props. This is simple and fast, because only that part of the tree renders.
Do not move state to a global store “just in case”. Global state is harder to follow: any component can change it, and more components render when it changes.
If you pass the same prop through many layers only to reach a deep child, first try composition: pass the child itself as children, so the middle layers do not need the prop.
Context: for values that change rarely
Context sends a value to every component under a provider, without props. But every component that reads a context renders again when its value changes, and memo does not stop that.
So context is great for values that change rarely: theme, language, the signed-in user. For data that changes often, like the cart, keep these rules:
- Split contexts by how often the data changes: one for cart items, one for cart actions, one for the theme.
- Keep the value stable with useMemo, so a new object is not made on every render of the provider.
An external store with selectors
When many components read small parts of data that changes often, use a small store such as Zustand or Redux Toolkit. Each component subscribes with a selector and renders only when the selected part changes.
import { create } from 'zustand';
type CartItem = { productId: string; quantity: number };
type CartStore = {
items: CartItem[];
add: (productId: string) => void;
};
export const useCart = create<CartStore>()(set => ({
items: [],
add: productId =>
set(s => ({ items: [...s.items, { productId, quantity: 1 }] })),
}));
// The badge renders only when the count changes.
export function CartBadge() {
const count = useCart(s => s.items.length);
return <span className="badge">{count}</span>;
}
// A product card never renders because of the cart.
export function AddButton({ id }: { id: string }) {
const add = useCart(s => s.add);
return <button onClick={() => add(id)}>Add to cart</button>;
}
- The selector
s => s.items.lengthreturns a number. After each change the store compares the old and the new number with Object.is. - If a selector returns a new object or array every time, the component renders on every change. In Zustand 5 this can even cause an endless loop. Select single values, or use useShallow.
- These stores use the useSyncExternalStore hook inside, so they are safe with concurrent rendering.
Server state: a cache, not a store
Copying server data into a global store with useEffect is the most common mistake. You must then handle loading, errors, old data, two components fetching the same thing, and refetching after a change, all by hand. A server-state library does this for you.
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function useProduct(id: string) {
return useQuery({
queryKey: ['product', id],
queryFn: () => fetch(`/api/products/${id}`).then(r => r.json()),
staleTime: 60_000, // fresh for one minute
});
}
function useUpdatePrice() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (p: { id: string; price: number }) =>
fetch(`/api/products/${p.id}`, {
method: 'PATCH',
body: JSON.stringify({ price: p.price }),
}),
onSuccess: (_data, p) =>
queryClient.invalidateQueries({ queryKey: ['product', p.id] }),
});
}
- The query key names the data. All components that use the key [‘product’, ‘42’] share one cache entry and one request.
- staleTime says how long the data counts as fresh. While fresh, no new request is sent. When it is stale, the cache shows the old data at once and fetches new data in the background.
- Invalidation after a mutation marks the key as stale and refetches it. This fixes the “old price” bug in this browser. For other users, use a short staleTime, refetch on window focus (on by default), or push changes from the server.
- If you use a router with loaders, or a framework like Next.js, data can also come from the loader or a server component. The rule is the same: server data has one owner, and the browser keeps a cache.
URL state: the filters belong in the address
import { useSearchParams } from 'react-router';
export function Filters() {
const [params, setParams] = useSearchParams();
const color = params.get('color') ?? 'all';
return (
<select
value={color}
onChange={e => setParams(p => { p.set('color', e.target.value); return p; })}
>
<option value="all">All colors</option>
<option value="red">Red</option>
</select>
);
}
- The URL is the single source of truth. A shared link, a bookmark, the back button and a page reload all work.
- Do not copy the URL value into useState. Read it from the URL on every render.
- Keep only small, meaningful values in the URL. A half-typed text can stay in local state and go to the URL after a short pause or on submit.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| All state in one global store | Hard to follow, many extra renders. | Put each kind of state in its own home. |
| Copying fetched data into a store with useEffect | Old data, double requests, manual loading flags. | A server-state cache (TanStack Query) or loaders. |
| One big context with a new value on every render | Every reader renders on every change. | Split contexts and keep values stable. |
| A selector that returns a new object | The component renders on every store change. | Select single values, or use useShallow. |
| Filters only in useState | Sharing, back button and reload lose them. | Keep them in the URL search params. |
| The same data in two places | The two copies get out of sync. | One owner. Compute the rest during render. |
Summary in 6 lines
- Sort state into four kinds: local UI, server, URL and shared client state.
- Start local. Lift state up only as far as needed, and use composition before context.
- Use context for values that change rarely. Split it and keep the value stable.
- For data that changes often and is read in many places, use a small store with selectors.
- Server data belongs in a cache with keys, freshness and invalidation, not in a hand-made store.
- Anything people share or go back to (filters, page, search) belongs in the URL.