React State Management: Zustand, Jotai, TanStack Query
How to choose and combine React state management tools: Context API, Zustand, Jotai, and TanStack Query for server state, with patterns and a decision framework.
Introduction
Something feels off when your “state management” setup has a useEffect that fetches /api/products, dumps the result into a Zustand store, and a second useEffect that refetches it every time a component mounts. You’ve built a cache, badly. No request deduplication, no stale-while-revalidate, no retry logic, no way to invalidate anything when a mutation succeeds. Meanwhile your actual client state — the open modal, the cart, the theme — is fighting for space in the same store.
That’s the trap this guide is about. React state management isn’t one decision, it’s two: split server state from client state first, then pick a tool for each. Get the first split wrong and no library will rescue you — you’ll end up reimplementing TanStack Query inside Redux and wondering why the app feels janky.
We’ll cover the tools that matter in 2025–2026: the built-in Context API, Zustand v5, Jotai, and TanStack Query v5, plus an honest look at why Redux Toolkit — the incumbent for over a decade — lost mindshare. Redux Toolkit and React Query v4 are still everywhere in older codebases, so the mental model transfers even though the APIs have moved on. By the end you’ll have a decision framework you can apply to your next project, not just a feature list.
Prerequisites: you’re comfortable with React 18+ hooks (useState, useEffect, useReducer), you know TypeScript basics, and you’ve felt prop drilling or re-render waterfalls at least once. If Server Components are new to you, the React Server Components guide covers that world; this guide stays on the client side.
First, Split Server State from Client State
Before comparing libraries, one distinction does most of the work. Server state is data your app doesn’t own: API responses, paginated lists, user profiles, search results. It lives on a server somewhere, it goes stale while you look at it, it can be refetched, and it needs caching, deduplication, and invalidation to behave well. Client state is data the browser owns outright: UI toggles, form drafts, the theme, animation flags.
The boundary gets blurry in a few places. A shopping cart is usually client state that syncs to the server through mutations. An auth token lives in localStorage (client state) while the user profile behind it is server state. The rule of thumb isn’t “which library,” it’s “who owns this data and how does it change.” If the answer involves a network request, it belongs in a server-state cache.
Here’s why the split matters in practice. Server state has requirements that client stores simply don’t solve: automatic caching keyed by query, deduplication of identical in-flight requests, background refetching when the window regains focus, pagination cursors, optimistic rollback on failure. If you put products in Zustand, you write all of that yourself — and you will write it worse than the library that exists for exactly this job. The React performance optimization guide covers the re-render side of this problem; this section is about the data side.
A quick reference for where things usually land:
| Kind of state | Examples | Right home |
|---|---|---|
| Server state | Products, orders, user profile, search results | TanStack Query |
| Shared client state | Theme, locale, auth session, cart | Context, Zustand, or Jotai |
| Local state | Modal open, input value, hover, focus | useState / useReducer |
The rest of this guide walks through each tool, then ties them together with a comparison and a decision framework.
Context API
Context is React’s built-in answer to prop drilling, and for a lot of apps it’s all you need. createContext defines a channel, a provider broadcasts a value, and useContext subscribes consumers to it. The React docs on createContext are the canonical reference; the short version is that context is designed for values that change rarely — theme, locale, authenticated user, feature flags.
Here’s the basic shape, with one fix already applied that the original examples always seem to skip:
// ThemeContext.tsx — built-in React context for low-frequency shared state
import { createContext, useContext, useMemo, useState, type ReactNode } from "react";
type Theme = "light" | "dark";
interface ThemeContextValue {
theme: Theme;
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
const toggleTheme = () => setTheme((t) => (t === "light" ? "dark" : "light"));
// Without useMemo, value is a new object every render, and React sees a
// "changed" context — re-rendering every consumer even when nothing did.
const value = useMemo(() => ({ theme, toggleTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const context = useContext(ThemeContext);
if (!context) throw new Error("useTheme must be used within ThemeProvider");
return context;
}
// Usage
function ThemedButton() {
const { theme, toggleTheme } = useTheme();
return (
<button
onClick={toggleTheme}
className={theme === "dark" ? "bg-slate-800 text-white" : "bg-white text-slate-900"}
>
Toggle theme (current: {theme})
</button>
);
}
That useMemo isn’t optional polish — it’s the difference between Context working and Context being a re-render machine. React compares context values by reference (Object.is). If you pass value={{ theme, toggleTheme }} inline, every render of the provider creates a new object, React treats it as a change, and every consumer re-renders. Memoizing keeps the reference stable until theme actually changes. This is the single most common Context mistake, and it survives code review because the bug only shows up as sluggishness, not an error. For when memoization pays off versus when it’s just overhead, see When to Use useMemo and useCallback.
The second trap is granularity. Context has no selectors — there’s no way for a consumer to say “I only care about theme, not toggleTheme.” Any change to the value re-renders the whole consumer subtree. The fix is architectural: split unrelated state into separate providers. A ThemeProvider and a CartProvider can coexist; a cart update shouldn’t re-render every themed component.
For state with real transition logic — a cart that adds, removes, and recalculates totals — useReducer keeps the reducer pure and testable. The React docs on useReducer cover the pattern; here’s the shape applied to a cart:
// CartContext.tsx — complex client state managed with useReducer
import {
createContext,
useContext,
useMemo,
useReducer,
type Dispatch,
type ReactNode,
} from "react";
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
type CartAction =
| { type: "ADD_ITEM"; item: Omit<CartItem, "quantity"> }
| { type: "REMOVE_ITEM"; id: string }
| { type: "UPDATE_QUANTITY"; id: string; quantity: number }
| { type: "CLEAR" };
interface CartState {
items: CartItem[];
total: number;
}
function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case "ADD_ITEM": {
const existing = state.items.find((i) => i.id === action.item.id);
const items = existing
? state.items.map((i) =>
i.id === action.item.id ? { ...i, quantity: i.quantity + 1 } : i
)
: [...state.items, { ...action.item, quantity: 1 }];
return { items, total: items.reduce((s, i) => s + i.price * i.quantity, 0) };
}
case "REMOVE_ITEM": {
const items = state.items.filter((i) => i.id !== action.id);
return { items, total: items.reduce((s, i) => s + i.price * i.quantity, 0) };
}
case "UPDATE_QUANTITY": {
const items = state.items
.map((i) => (i.id === action.id ? { ...i, quantity: Math.max(0, action.quantity) } : i))
.filter((i) => i.quantity > 0);
return { items, total: items.reduce((s, i) => s + i.price * i.quantity, 0) };
}
case "CLEAR":
return { items: [], total: 0 };
default:
return state;
}
}
const CartContext = createContext<{
state: CartState;
dispatch: Dispatch<CartAction>;
} | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
const [state, dispatch] = useReducer(cartReducer, { items: [], total: 0 });
// dispatch is stable across renders; state isn't. Memoize the wrapper
// object so consumers only re-render when the cart actually changes.
const value = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
}
export function useCart() {
const context = useContext(CartContext);
if (!context) throw new Error("useCart must be used within CartProvider");
return context;
}
When is Context the right call? Small-to-medium apps, low-frequency updates, and anywhere you’d rather add zero dependencies. When is it wrong? Anywhere updates fire rapidly — a live form, a drag-and-drop canvas, a chat feed — because every keystroke re-renders every consumer. If your app has outgrown Context, the next two tools are the usual suspects.
Zustand
Zustand is a tiny store that lives outside the React tree. You create it once with create(), and components subscribe through hooks that take a selector. Version 5 is current; the curried create<T>()(...) syntax shown below is what TypeScript projects should use so middleware typing stays intact.
The subscription model is the whole point, so it’s worth understanding precisely. useUserStore((s) => s.user) doesn’t subscribe to the store — it subscribes to the result of that selector. Under the hood, Zustand is built on useSyncExternalStore, the React primitive designed exactly for external stores: React calls your selector, compares the output, and only re-renders the component if it changed. Two components selecting different slices never interfere. The official Zustand demo shows the vanilla (non-React) usage — the same store works in event handlers, timers, and tests without any provider.
// store/useUserStore.ts — lightweight global client state, no provider needed
import { create } from "zustand";
interface UserStore {
user: { id: string; name: string; email: string } | null;
setUser: (user: UserStore["user"]) => void;
logout: () => void;
}
export const useUserStore = create<UserStore>()((set) => ({
user: null,
setUser: (user) => set({ user }),
logout: () => set({ user: null }),
}));
// Usage — subscribe to exactly the slice you need
function UserProfile() {
const user = useUserStore((s) => s.user);
const logout = useUserStore((s) => s.logout);
if (!user) return <p>Not logged in</p>;
return (
<div>
<p>{user.name}</p>
<button onClick={logout}>Logout</button>
</div>
);
}
For anything beyond trivial state, middleware does the heavy lifting. persist syncs to localStorage (great for carts and preferences), immer lets you write mutable-looking updates, and devtools connects to the Redux DevTools browser extension:
// store/useCartStore.ts — Zustand with persist and immer middleware
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
interface CartStore {
items: CartItem[];
total: number;
addItem: (item: Omit<CartItem, "quantity">) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
clear: () => void;
}
const recalcTotal = (items: CartItem[]) =>
items.reduce((sum, i) => sum + i.price * i.quantity, 0);
export const useCartStore = create<CartStore>()(
devtools(
persist(
immer((set) => ({
items: [],
total: 0,
addItem: (item) =>
set((state) => {
const existing = state.items.find((i) => i.id === item.id);
if (existing) {
existing.quantity += 1;
} else {
state.items.push({ ...item, quantity: 1 });
}
state.total = recalcTotal(state.items);
}),
removeItem: (id) =>
set((state) => {
state.items = state.items.filter((i) => i.id !== id);
state.total = recalcTotal(state.items);
}),
updateQuantity: (id, quantity) =>
set((state) => {
const item = state.items.find((i) => i.id === id);
if (item) item.quantity = Math.max(0, quantity);
state.items = state.items.filter((i) => i.quantity > 0);
state.total = recalcTotal(state.items);
}),
clear: () =>
set((state) => {
state.items = [];
state.total = 0;
}),
})),
{ name: "cart-storage" } // localStorage key
),
{ name: "CartStore" } // label shown in Redux DevTools
)
);
The selector discipline is where performance is won or lost:
// Select only what you need — prevents unnecessary re-renders
import { useCartStore } from "../store/useCartStore";
function CartBadge() {
// Re-renders only when `total` changes, not on every cart update.
const total = useCartStore((s) => s.total);
return <span>{total > 0 ? `$${total}` : "Empty"}</span>;
}
function CartList() {
// Re-renders only when `items` changes.
const items = useCartStore((s) => s.items);
return (
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} × {item.quantity}
</li>
))}
</ul>
);
}
One sharp edge: selectors returning objects or arrays create a new reference on every call, so useCartStore((s) => ({ items: s.items, total: s.total })) re-renders constantly — the comparison always fails. Zustand ships useShallow for exactly this case; it does a shallow equality check instead of reference equality:
import { useCartStore } from "../store/useCartStore";
import { useShallow } from "zustand/react/shallow";
function CartSummary() {
// useShallow compares each field, so this only re-renders when
// items, total, or clear actually change.
const { items, total, clear } = useCartStore(
useShallow((s) => ({ items: s.items, total: s.total, clear: s.clear }))
);
return (
<div>
<p>
{items.length} items — ${total}
</p>
<button onClick={clear}>Clear cart</button>
</div>
);
}
Why did Zustand eat Redux’s lunch? Three reasons, none of them ideological. The bundle is around a kilobyte gzipped versus a dozen-plus for Redux plus React-Redux. There’s no boilerplate — no actions, no reducers, no dispatch ceremony, just functions that call set. And the mental model is “a hook that reads a slice of an object,” which every React developer already understands. When you want the profiler side of slice-driven rendering, the React performance optimization guide covers it.
Jotai
Jotai takes the opposite approach from Zustand: instead of one store you slice with selectors, state is broken into small atoms — units of state that components subscribe to individually. The Jotai docs describe the model well; the payoff is granular reactivity. Change one atom and only components reading that atom (or atoms derived from it) re-render. Everything else is untouched.
// atoms.ts — fine-grained reactive state
import { atom, useAtom, useAtomValue, useSetAtom } from "jotai";
// Primitive atom — a single value
const countAtom = atom(0);
// Derived atom (read-only) — recomputes when countAtom changes
const doubleCountAtom = atom((get) => get(countAtom) * 2);
// Derived atom (read-write) — exposes a custom update action
const incrementAtom = atom(
(get) => get(countAtom),
(get, set) => set(countAtom, get(countAtom) + 1)
);
// The current user id lives in a separate module in a real app
// (it typically comes from your auth store); defined here so this
// snippet compiles standalone.
const currentUserIdAtom = atom<string>("user-1");
// Async derived atom — suspends the component while fetching
const userDataAtom = atom(async (get) => {
const userId = get(currentUserIdAtom);
const res = await fetch(`/api/users/${userId}`);
return res.json();
});
// Usage — each hook subscribes to a different granularity
function Counter() {
const [count, setCount] = useAtom(countAtom);
const double = useAtomValue(doubleCountAtom);
const increment = useSetAtom(incrementAtom);
return (
<div>
<p>
Count: {count} (doubled: {double})
</p>
<button onClick={increment}>+1</button>
</div>
);
}
Derived atoms are where Jotai earns its keep. Dependency tracking is automatic — doubleCountAtom knows it depends on countAtom, and when countAtom changes, anything reading doubleCountAtom re-renders. No manual selector wiring, no useMemo chains holding the graph together. For per-entity state, atomFamily generates one atom per key, which is perfect for “state per product ID” or “state per row”:
// One independent atom per item ID — ProductItem({id}) only
// re-renders when its own atom changes.
import { atomFamily, useAtom } from "jotai";
const itemAtomFamily = atomFamily((id: string) =>
atom<{ id: string; name: string; price: number } | null>(null)
);
function ProductItem({ id }: { id: string }) {
const [item, setItem] = useAtom(itemAtomFamily(id));
return <div>{item?.name}</div>;
}
The honest trade-off: Jotai is brilliant for complex, interdependent state graphs — filters feeding derived lists, per-entity editing state, wizard flows — and overkill for “a cart and a theme.” Splitting simple state into dozens of atoms fragments your mental model; a single Zustand store is easier to navigate. If your state is mostly independent atoms with a few derivations, reach for Jotai. If it’s a handful of related slices, Zustand is simpler.
TanStack Query
TanStack Query (formerly React Query) is the tool for the category we defined at the top: server state. Version 5 is current, and its whole job is to be the cache layer your hand-rolled useEffect + useState never was. The docs at tanstack.com/query are excellent; here’s the lifecycle worth internalizing.
Every query is identified by a queryKey — an array like ["products"] or ["products", page]. The key is the cache address: two components calling useQuery with the same key share one request, one cache entry, one lifecycle. That’s deduplication for free. Around that key sit the timing knobs:
staleTime— how long data is considered fresh. While fresh, mounting a component won’t refetch. Default is0, meaning data is stale immediately and refetches on every mount.gcTime— how long an inactive query stays in the cache before garbage collection. Default is 5 minutes in v5 (it wascacheTimein v4 — same idea, renamed).- Refetch triggers — window focus, reconnect, and interval refetches are configurable per query.
// hooks/useProducts.ts — server state with caching, dedup, and retries
import { useQuery } from "@tanstack/react-query";
export interface Product {
id: string;
name: string;
price: number;
}
async function fetchProducts(): Promise<Product[]> {
const res = await fetch("/api/products");
if (!res.ok) throw new Error("Failed to fetch products");
return res.json();
}
export function useProducts() {
return useQuery({
queryKey: ["products"],
queryFn: fetchProducts,
staleTime: 5 * 60 * 1000, // fresh for 5 minutes — no refetch on remount
gcTime: 30 * 60 * 1000, // keep inactive cache for 30 minutes
});
}
// Usage
function ProductList() {
const { data, isPending, error, refetch } = useProducts();
if (isPending) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<button onClick={() => refetch()}>Refresh</button>
<ul>
{data?.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}
Note isPending instead of isLoading — v5 renamed the flags so “pending” means “no data yet” and “fetching” means “a request is in flight,” which lets you show stale data with a subtle loading indicator instead of a full spinner. If you’re porting v4 code, that’s the rename to watch for.
Mutations are where invalidation comes in. After a successful write, you tell the cache which queries are now suspect:
// hooks/useCreateProduct.ts — mutation with automatic cache invalidation
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Product } from "./useProducts";
async function createProduct(data: Omit<Product, "id">): Promise<Product> {
const res = await fetch("/api/products", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error("Failed to create product");
return res.json();
}
export function useCreateProduct() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: createProduct,
onSuccess: () => {
// Mark every ["products"] query stale — mounted observers refetch.
queryClient.invalidateQueries({ queryKey: ["products"] });
},
});
}
function AddProductForm() {
const createProduct = useCreateProduct();
return (
<form
onSubmit={(e) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
createProduct.mutate({
name: formData.get("name") as string,
price: Number(formData.get("price")),
});
}}
>
<input name="name" required />
<input name="price" type="number" required />
<button type="submit" disabled={createProduct.isPending}>
{createProduct.isPending ? "Creating..." : "Create"}
</button>
{createProduct.error && <p>Error: {createProduct.error.message}</p>}
</form>
);
}
The pattern worth memorizing is snapshot → mutate → settle: snapshot the current cache, apply the change optimistically, roll back on error, invalidate on settle. It gives users instant feedback while keeping the server as the source of truth:
// hooks/useUpdateProduct.ts — optimistic update with rollback
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Product } from "./useProducts";
export function useUpdateProduct() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: Product) =>
fetch(`/api/products/${data.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
}).then((r) => r.json()),
onMutate: async (updatedProduct) => {
// Cancel in-flight refetches so they can't overwrite our optimistic write.
await queryClient.cancelQueries({ queryKey: ["products"] });
// Snapshot the previous value for rollback.
const previousProducts = queryClient.getQueryData<Product[]>(["products"]);
// Write the update straight into the cache — the UI updates instantly.
queryClient.setQueryData<Product[]>(["products"], (old) =>
old?.map((p) => (p.id === updatedProduct.id ? updatedProduct : p))
);
// Return context so onError can restore the snapshot.
return { previousProducts };
},
onError: (err, updatedProduct, context) => {
// Server rejected the write — put the old data back.
queryClient.setQueryData(["products"], context?.previousProducts);
},
onSettled: () => {
// Whether it succeeded or failed, resync with the server.
queryClient.invalidateQueries({ queryKey: ["products"] });
},
});
}
The optimistic update pattern goes deeper on conflict resolution and when optimism is safe versus when it lies to the user.
Pagination is the last piece of the query lifecycle worth showing. placeholderData: keepPreviousData keeps the old page visible while the next one loads — without it, every page change flashes a spinner and the list collapses, which feels broken:
// hooks/usePaginatedProducts.ts — page-based and infinite-scroll queries
import { keepPreviousData, useInfiniteQuery, useQuery } from "@tanstack/react-query";
import type { Product } from "./useProducts";
export function usePaginatedProducts(page: number) {
return useQuery({
queryKey: ["products", page],
queryFn: () => fetch(`/api/products?page=${page}`).then((r) => r.json()),
placeholderData: keepPreviousData, // show stale page while fetching the next
});
}
export function useInfiniteProducts() {
return useInfiniteQuery({
queryKey: ["products", "infinite"],
queryFn: ({ pageParam = 1 }) =>
fetch(`/api/products?page=${pageParam}`).then((r) => r.json()),
initialPageParam: 1,
getNextPageParam: (lastPage) => lastPage.nextPage ?? undefined,
});
}
function InfiniteProductList() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isPending } =
useInfiniteProducts();
if (isPending) return <div>Loading...</div>;
return (
<div>
{data?.pages.map((page) =>
page.items.map((product: Product) => (
<div key={product.id}>{product.name}</div>
))
)}
<button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
{isFetchingNextPage ? "Loading..." : "Load more"}
</button>
</div>
);
}
The guard on data?.pages matters: isPending covers the no-data-yet case, but TypeScript still types data as possibly undefined, and a background refetch can briefly leave it so. Optional chaining is cheaper than a crash.
Why Redux Fell Behind
No honest comparison skips Redux, because for years “React state management” and “Redux” were synonyms. Understanding why it lost mindshare explains most of the current ecosystem — and prevents you from cargo-culting either direction.
Redux’s core idea is a single immutable store, updated only through dispatched actions handled by pure reducers. Redux Toolkit wrapped that in createSlice and configureStore, which removed most of the boilerplate, and it became the standard around 2019 — the official docs are still the reference if you’re maintaining a Redux app. It worked. What changed was everything around it.
First, server state left the building. The original reason apps reached for Redux was to cache API responses — normalize them, dedupe them, keep them fresh. RTK Query answered that inside Redux, but TanStack Query answered it better: smaller API surface, first-class suspense and infinite-query support, and a mental model (“a cache with observers”) that’s simpler than “a store you sync with a cache.” Once server state had a dedicated home, Redux’s biggest justification shrank.
Second, client state got simpler. React hooks plus Context covered small apps; Zustand and Jotai covered the rest with a fraction of the ceremony. Redux asks you to learn actions, reducers, selectors, middleware, normalization, and immutability discipline before you write a line of feature code. Zustand asks you to write a function that calls set. That’s not a small difference in onboarding — it’s the difference between an afternoon and a week.
Third, the bundle math stopped working. Redux + React-Redux + RTK lands around 12–15 kB gzipped; Zustand is roughly a kilobyte, Jotai a few. On mobile connections, that’s real.
To be fair to Redux: its DevTools are still the best in the ecosystem — time-travel debugging, action replay, state diffing — and RTK’s conventions scale well in large teams where you want enforced patterns. Huge existing codebases shouldn’t rewrite for fashion. The mistake isn’t Redux itself; it’s reaching for it in a new project in 2026 when the problem is server state (use TanStack Query) or simple client state (use Zustand or Context).
Choosing a Tool
Here’s the comparison in one place. Bundle sizes are approximate min+gzip and vary by version and what you import — treat them as order-of-magnitude, not gospel.
| Tool | Approx. size | Learning curve | Re-render model | DevTools | Best for | When to avoid |
|---|---|---|---|---|---|---|
| Context API | 0 (built-in) | None | All consumers on value change | React DevTools | Theme, locale, auth, low-frequency | High-frequency updates, deep trees |
| Zustand | ~1 kB | Low | Per-selector slice | Redux DevTools | Global client state, cart, session | Fine-grained atomic graphs |
| Jotai | ~4 kB | Medium | Per-atom dependents | Jotai DevTools | Complex derived/atomic state | Simple stores — overkill |
| TanStack Query | ~13 kB | Medium | Per-queryKey observers | Query DevTools | All server state | Client-only state |
| Redux Toolkit | ~12 kB | High | Selector-based | Best in class | Large teams, strict conventions | New projects, small apps |
And here’s how each tool decides who re-renders — the mechanism underneath the marketing:
Now the framework, by scenario rather than by feature list:
- Small app or prototype.
useState+useReducerfor local state, one or two Context providers for theme/auth, and stop. Adding Zustand on day one is premature — you’ll have a store with two keys and a dependency you didn’t need. - Content or marketing site with a bit of interactivity. Same as above, plus TanStack Query if anything fetches data. Most “state management” problems on content sites are actually server-state problems wearing a client-state costume.
- E-commerce or dashboard with real data. TanStack Query owns everything that comes from the API — products, orders, user profile — with
staleTimetuned per resource. Zustand owns the cart, filters, and UI preferences. Optimistic updates on cart mutations. This is the most common production combo for a reason. - Real-time or collaborative UI. Jotai shines when state is a graph — presence indicators, per-cell edits, derived selections. Pair it with TanStack Query for the server side and watch your re-render counts in the profiler.
- Next.js with Server Components. The calculus shifts: server components can fetch during render, so some “server state” never needs a client cache. TanStack Query still wins for client-side navigation, mutations, and anything interactive. Context providers must live in client components, and the React Server Components guide explains the boundary rules.
The pattern across all five: one tool per category, not one tool per app. The teams that struggle are the ones who picked Redux in 2019 and still route form state through it in 2026.
Two things worth saying out loud before you move on. First, none of these tools are mutually exclusive in a way that hurts you — the cost of “one extra small store” is a kilobyte and a mental model you already have. Second, the decision isn’t permanent. Start with Context and TanStack Query; if profiling shows Context re-rendering too much, promote that slice to Zustand. Migrating a single store is an afternoon, not a rewrite.
Putting It Together
A realistic mini-store wires all three client-side tools at once — each owning its category:
// App.tsx — composing Context, Zustand, and TanStack Query
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "./ThemeContext";
import { useCartStore } from "./store/useCartStore";
import { useProducts } from "./hooks/useProducts";
const queryClient = new QueryClient({
defaultOptions: {
queries: { staleTime: 60 * 1000, retry: 1 },
},
});
function Storefront() {
// Server state: products come from the query cache.
const { data: products } = useProducts();
// Client state: cart lives in the Zustand store, persisted to localStorage.
const addItem = useCartStore((s) => s.addItem);
const total = useCartStore((s) => s.total);
return (
<main>
<h1>Storefront</h1>
<ul>
{products?.map((p) => (
<li key={p.id}>
{p.name} — ${p.price}
<button onClick={() => addItem({ id: p.id, name: p.name, price: p.price })}>
Add
</button>
</li>
))}
</ul>
<footer>Cart total: ${total}</footer>
</main>
);
}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider>
<Storefront />
</ThemeProvider>
</QueryClientProvider>
);
}
Notice what’s not here: no cart in the query cache (it’s client state that syncs via mutations), no products in Zustand (that’s server state), no prop drilling (Context and stores handle it), and no global useState soup. Each piece sits where the first section’s diagram told it to.
Best Practices
- Split server state from client state before choosing libraries. If a
useEffectfetches data into a client store, you’re rebuilding TanStack Query with bugs. - Use TanStack Query for every API read and write. Caching, dedup, retries, invalidation, and optimistic updates come free — don’t hand-roll them.
- Subscribe with selectors in Zustand, and wrap object selectors in
useShallow. The defaultuseStore()subscribes to everything and re-renders on any change. - Memoize Context values and split providers by domain. Inline
value={{ ... }}objects and monolithic providers are the two ways Context becomes a performance bug. - Tune
staleTimedeliberately and invalidate on mutations. The v5 defaults are sane for demos and wrong for production — decide per resource how fresh data must be. - Reach for
useSyncExternalStore-aware libraries (Zustand, Jotai, and TanStack Query all are) so React 18/19 subscribes to external stores tear-free and correctly.
Common Mistakes
- Putting server state in Zustand or Context. You lose caching, deduplication, and refetching, and you inherit stale-data bugs. Server state belongs in TanStack Query.
- One giant Context provider. Every state change re-renders every consumer. Split by domain — theme, auth, cart — and memoize each value.
- Inline context values without
useMemo.value={{ theme }}creates a new object every render, so React thinks the context changed every time. This is the most common Context performance bug. useCartStore()with no selector. Subscribing to the whole store re-renders the component on every update. Always select the slice you need.- Leaving
staleTimeat the default of 0. Every mount refetches. For most read-heavy resources, 30 seconds to 5 minutes is a better starting point. - Skipping
onMutatesnapshots on optimistic updates. Without the snapshot andonErrorrollback, a failed mutation leaves the UI lying about server state until the next refetch. - Using Jotai atoms for everything. Dozens of micro-atoms for simple state fragments your mental model. One Zustand store is easier to reason about until you actually need atomic granularity.
See Also
Frequently Asked Questions
Do I still need Redux?
For new projects, almost never. Redux Toolkit is still excellent for large teams that need enforced conventions and best-in-class DevTools, and existing Redux codebases should stay put rather than rewrite for fashion. But for a new app in 2026, TanStack Query covers server state and Zustand or Jotai covers client state with a fraction of the boilerplate and bundle size.
TanStack Query vs Redux for server state?
TanStack Query, and it's not close for most teams. Both can cache server data, but TanStack Query is purpose-built for it: query keys instead of normalized slices, built-in dedup and refetch triggers, suspense support, and a much smaller API to learn. Redux + RTK Query still works — it's a legitimate choice inside an existing Redux app — but adopting Redux just for server state means taking on the whole client-state machinery you don't need.
Context vs Zustand — which should I use?
Context for low-frequency updates in small-to-medium trees: theme, locale, auth, feature flags. Zustand when updates are frequent, the tree is deep, or you need selectors to prevent re-renders. A good heuristic: if changing the value would visibly jank the UI, it's too hot for Context.
What is an optimistic update?
Updating the UI immediately, before the server confirms the mutation, then reconciling when the response arrives. If the server errors, the UI rolls back to the previous state. It trades a brief lie for perceived speed — great for likes, cart adds, and toggles; risky for payments and anything where a wrong optimistic state could mislead the user into another action.
Can I use multiple state management tools together?
Not only can you, you should. The standard production setup is TanStack Query for server state, Zustand or Jotai for global client state, Context for low-frequency cross-cutting concerns like theme, and useState/useReducer for anything local. The failure mode isn't mixing tools — it's forcing one tool to do every job.
Related Resources
Complete Guide to React Performance Optimization
Optimize React apps for speed. Covers memoization, virtualization, code splitting, bundle analysis, React Profiler, concurrent features, and Core Web Vitals.
GuideComplete Guide to React Server Components: RSC Architecture
A deep dive into React Server Components: the RSC payload, server-client boundaries, data loading, streaming, Next.js caching, and server actions.
GuideComplete Guide to React 19 Features
A practical walkthrough of React 19: server components, the use() hook, actions, ref as a prop, document metadata, asset loading, and the React Compiler.
GuideTypeScript Advanced Types: The Complete Guide
TypeScript advanced types in depth: conditional types, infer, mapped types, template literals, satisfies, variance, narrowing, and tested real-world patterns.
PatternOptimistic Update Pattern
How to update UI instantly and reconcile with the server in React: rollback on error, temp IDs, conflict handling, React 19 useOptimistic, and React Query.
RecipeReact useMemo and useCallback: When to Use Them
Learn when useMemo and useCallback help React rendering, when they add work, and what React Compiler changes about manual memoization.