Skip to main content

Lesson 3 of 9

Zustand - Lightweight Global State

Zustand is the modern alternative to Redux for global client state. It's tiny (< 1KB), requires no boilerplate, and integrates with Redux DevTools. The key insight: Zustand stores are just hooks - any component can read or update them without providers.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Zustand - Store, Selectors & Slices

Zustand - Store, Selectors & Slices
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

// ---- Cart Store ----
interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
}

interface CartStore {
  items: CartItem[];
  addItem: (item: Omit<CartItem, 'quantity'>) => void;
  removeItem: (id: string) => void;
  updateQuantity: (id: string, quantity: number) => void;
  clear: () => void;
  // Derived (computed)
  total: () => number;
  itemCount: () => number;
}

export const useCartStore = create<CartStore>()(
  devtools(
    persist(
      (set, get) => ({
        items: [],

        addItem: (item) => set(state => {
          const existing = state.items.find(i => i.id === item.id);
          if (existing) {
            return {
              items: state.items.map(i =>
                i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
              ),
            };
          }
          return { items: [...state.items, { ...item, quantity: 1 }] };
        }),

        removeItem: (id) => set(state => ({
          items: state.items.filter(i => i.id !== id),
        })),

        updateQuantity: (id, quantity) => set(state => ({
          items: quantity <= 0
            ? state.items.filter(i => i.id !== id)
            : state.items.map(i => i.id === id ? { ...i, quantity } : i),
        })),

        clear: () => set({ items: [] }),

        // Getters (derived - access current state via get())
        total: () => get().items.reduce((sum, i) => sum + i.price * i.quantity, 0),
        itemCount: () => get().items.reduce((sum, i) => sum + i.quantity, 0),
      }),
      { name: 'cart-storage' } // persist to localStorage
    ),
    { name: 'cart-store' } // devtools label
  )
);

// ---- Using the store in components ----
// Selector pattern - subscribe only to the slice you need
function CartButton() {
  // โœ… Only re-renders when itemCount changes
  const itemCount = useCartStore(state => state.itemCount());
  return <button>๐Ÿ›’ {itemCount}</button>;
}

function ProductCard({ product }: { product: Product }) {
  const addItem = useCartStore(state => state.addItem);
  return (
    <button onClick={() => addItem({ id: product.id, name: product.name, price: product.price })}>
      Add to Cart
    </button>
  );
}

// ---- Slice pattern - split large stores ----
interface UserSlice {
  user: User | null;
  setUser: (user: User | null) => void;
}

interface SettingsSlice {
  theme: 'light' | 'dark';
  language: string;
  setTheme: (theme: 'light' | 'dark') => void;
}

// Combine slices into one store while keeping logic separated
export const useAppStore = create<UserSlice & SettingsSlice>()(
  devtools((...args) => ({
    ...createUserSlice(...args),
    ...createSettingsSlice(...args),
  }))
);

Common Mistakes - Zustand

  • Subscribing to the whole store - `const store = useCartStore()` re-renders on ANY store change; always select a specific slice: `const items = useCartStore(s => s.items)`
  • Computed values without memoization - defining a getter that derives expensive values from state will recompute on every render of the consumer; either compute in the component with useMemo or use the `zustand/middleware` subscribeWithSelector
  • Mutating state directly inside set - Zustand's set() doesn't auto-produce immutable updates; always spread: `set(s => ({ items: [...s.items, newItem] }))` not `s.items.push(newItem)`
  • Over-globalizing - not everything belongs in Zustand; form inputs, UI toggles, and hover states should remain local

Tip

Tip

Practice Zustand Lightweight Global State in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Zustand - Lightweight Global State

Practice Task

Note

Practice Task - (1) Write a working example of Zustand Lightweight Global State from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Zustand Lightweight Global State is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • Zustand is the modern alternative to Redux for global client state.
  • Subscribing to the whole store - `const store = useCartStore()` re-renders on ANY store change; always select a specific slice: `const items = useCartStore(s => s.items)`
  • Computed values without memoization - defining a getter that derives expensive values from state will recompute on every render of the consumer; either compute in the component with useMemo or use the `zustand/middleware` subscribeWithSelector
  • Mutating state directly inside set - Zustand's set() doesn't auto-produce immutable updates; always spread: `set(s => ({ items: [...s.items, newItem] }))` not `s.items.push(newItem)`

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done