Script Valley
React.js: Complete Course
State Management with Zustand and React QueryLesson 6.2

Zustand: global state management without boilerplate

Zustand create function, store definition, state and actions together, useStore hook, selectors, shallow equality, devtools middleware, persist middleware

Zustand: Minimal Global State

Zustand is a small state management library with zero boilerplate. Define your store โ€” state and actions together โ€” and use it in any component without wrapping your app in providers.

Creating a Store

npm install zustand
import { create } from 'zustand';

const useCartStore = create((set, get) => ({
  items: [],
  totalItems: 0,

  addItem: (product) => set(state => ({
    items: [...state.items, product],
    totalItems: state.totalItems + 1,
  })),

  removeItem: (id) => set(state => ({
    items: state.items.filter(item => item.id !== id),
    totalItems: state.totalItems - 1,
  })),

  clearCart: () => set({ items: [], totalItems: 0 }),
}));

// Usage in any component โ€” no Provider needed
function CartIcon() {
  const totalItems = useCartStore(state => state.totalItems);
  return <span>Cart ({totalItems})</span>;
}

function AddToCartButton({ product }) {
  const addItem = useCartStore(state => state.addItem);
  return <button onClick={() => addItem(product)}>Add</button>;
}

Select only the slice of state you need to avoid unnecessary re-renders. state => state.totalItems only re-renders when totalItems changes, not on every store update.

Up next

React Query: fetching and caching server data

Sign in to track progress

Zustand: global state management without boilerplate โ€” State Management with Zustand and React Query โ€” React.js: Complete Course โ€” Script Valley โ€” Script Valley