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 zustandimport { 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.
