Zustand
Zustand is a minimal, unopinionated state management library for React. It provides a store with no boilerplate.
Creating a store
ts
import { create } from 'zustand';
interface CounterStore {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
}
const useCounterStore = create<CounterStore>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));Using in components
tsx
function Counter() {
// subscribe to only what you need - no unnecessary re-renders
const count = useCounterStore((s) => s.count);
const increment = useCounterStore((s) => s.increment);
return <button onClick={increment}>{count}</button>;
}Async actions
ts
const useUserStore = create<UserStore>((set) => ({
user: null,
loading: false,
fetchUser: async (id) => {
set({ loading: true });
const user = await api.getUser(id);
set({ user, loading: false });
},
}));Zustand vs Redux
| Redux Toolkit | Zustand | |
|---|---|---|
| Boilerplate | Medium | Minimal |
| Bundle size | ~11kb | ~1kb |
| DevTools | Excellent | Good |
| Learning curve | Steep | Very low |
| Async | Thunk/Saga | Built-in |
| Architecture | Opinionated | Flexible |
| Best for | Large teams | Small-medium apps |
Zustand's selector pattern (
useStore(s => s.count)) is key - components only re-render when the selected slice changes, not the whole store.
updated
did you know it?