Part 33: Zustand: Modern, Lightweight Global State Management
Zustand (German for "state") is an extremely lightweight (under 2kB), fast, and intuitive state management library built on React hooks.
1. Why Developers Love Zustand
- Zero Boilerplate: No actions, no reducers, no providers wrapping the whole app.
- Selective Re-rendering: Components only re-render when their specific selected slice of state changes.
- Simplicity: You define a store with a single function call.
2. Creating a Store (cartStore.js)
npm install zustand
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export const useCartStore = create(
persist(
(set, get) => ({
items: [],
addItem: (product) => set((state) => ({
items: [...state.items, product]
})),
removeItem: (id) => set((state) => ({
items: state.items.filter(item => item.id !== id)
})),
clearCart: () => set({ items: [] }),
// Computed getter:
getTotalPrice: () => {
return get().items.reduce((sum, item) => sum + item.price, 0);
}
}),
{
name: 'shopping-cart-storage', // Saves to localStorage automatically!
}
)
);
3. Consuming the Store Anywhere
Notice that no <Provider> is required in your root component:
import { useCartStore } from './cartStore';
export default function CartBadge() {
// Atomic selector: Only re-renders when items.length changes
const itemCount = useCartStore((state) => state.items.length);
return (
<div className="cart-badge">
🛒 <span>{itemCount} items</span>
</div>
);
}
export function AddProductButton({ product }) {
const addItem = useCartStore((state) => state.addItem);
return (
<button onClick={() => addItem(product)} className="btn-add">
Add to Cart
</button>
);
}
Key Takeaways
- Zustand provides global state with almost zero boilerplate.
- Built-in middleware like
persistmakes caching tolocalStorageeffortless. - Use atomic selectors
state => state.fieldto optimize render cycles.
In Part 34, we will conquer server state caching with TanStack React Query!

