π» Zustand β Lightweight Global State for React
Zustand is a minimal, fast, and scalable state management library for React applications. It doesnβt require Context, reducers, or boilerplate code.
π 1. Installation
npm install zustand
π¦ 2. Create a Store
Define your global state using a simple function:
// store.js
import { create } from 'zustand';
const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
export default useCounterStore;
π§ 3. Use the Store in Components
Access the state and actions inside your components:
import useCounterStore from './store';
function Counter() {
const { count, increment, decrement } = useCounterStore();
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
);
}
βοΈ 4. Selectively Read State
To avoid unnecessary re-renders, you can subscribe to just part of the store:
const count = useCounterStore((state) => state.count);
β 5. Why Use Zustand?
- No Provider needed
- Simple API & great dev experience
- Fast and reactive
- Works well with async logic
- Perfect for small to medium projects