Hint
Store-based state with subscription model — only components subscribing to a specific slice re-render
import { create } from 'zustand';
// Define the store
const useCartStore = create((set, get) => ({
items: [],
total: 0,
addItem: (item) => set(state => ({
items: [...state.items, item],
total: state.total + item.price,
})),
removeItem: (id) => set(state => {
const item = state.items.find(i => i.id === id);
return {
items: state.items.filter(i => i.id !== id),
total: state.total - (item?.price ?? 0),
};
}),
clearCart: () => set({ items: [], total: 0 }),
}));
// Consume — component only re-renders when items changes
function CartBadge() {
const items = useCartStore(state => state.items); // subscribe to slice
return {items.length};
}
// Another component — only subscribes to total
function CartTotal() {
const total = useCartStore(state => state.total);
return ${total};
}
Zustand vs Context:
subscribeWithSelector middleware for more granular subscriptions.