← Back to the Build Your Homepage series
βš›οΈ
EPISODE 08
When to reach for Zustand / Redux / Jotai Β· TanStack Query for server state

Global State Management

Decide between local state, Context, and a state library. Compare Zustand, Redux Toolkit, and Jotai briefly, and use TanStack Query for server state.

state managementZustandReduxTanStack Query
Duration
⏱ About 2 hours
Level
πŸ“Š Intermediate+
Prerequisite
🎯 react-06
OUTCOME
Pick the right state tool for each use case and ship one with Zustand or TanStack Query

What you'll learn

  • 1Distinguish UI state from server state
  • 2Compare Zustand, Redux Toolkit, Jotai at a high level
  • 3Use TanStack Query for fetching, caching, revalidation
  • 4Know when Context is enough

1. Decision Tree

  • Local to one component? β†’ useState/useReducer
  • Shared across a small subtree? β†’ Context
  • Shared widely, changes often? β†’ state library (Zustand recommended for new projects)
  • Server data (caching/revalidation)? β†’ TanStack Query or SWR

2. Zustand (Tiny, Recommended)

tsx
import { create } from "zustand";

type Store = {
  count: number;
  increment: () => void;
  reset: () => void;
};

export const useCounter = create<Store>((set) => ({
  count: 0,
  increment: () => set(s => ({ count: s.count + 1 })),
  reset:     () => set({ count: 0 }),
}));

// Anywhere in the tree
function Counter() {
  const { count, increment } = useCounter();
  return <button onClick={increment}>Count: {count}</button>;
}

3. TanStack Query for Server State

tsx
import { useQuery } from "@tanstack/react-query";

function Users() {
  const { data, isLoading, error } = useQuery({
    queryKey: ["users"],
    queryFn: () => fetch("/api/users").then(r => r.json()),
    staleTime: 60_000,
  });

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error</p>;
  return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

Query handles caching, dedupe, refetch on focus, background revalidation, and pagination. Stop building this yourself.

4. Redux Toolkit (When You Need It)

Redux Toolkit is fine for large apps with complex actions, undo, time-travel debugging. For new small/medium apps, Zustand or Context is usually enough.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub β†—