Your First Zustand Store
Let us build our first global state store using Zustand. First, add the dependency to your project:
# Add Zustand package
npm install zustand1. Creating the Store
Create a store file named useCounterStore.ts inside src/stores/.
To define a store, use the create function from zustand. This function accepts a callback that registers state variables and updater actions:
// src/stores/useCounterStore.ts
import { create } from "zustand";
interface CounterState {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
}
// Create hook-based store
export const useCounterStore = create<CounterState>((set) => ({
// 1. Initial State values
count: 0,
// 2. Action triggers to modify state
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));2. Consuming the Store inside Components
Unlike Redux or Context, you do not need to wrap your application in a provider component. Simply import the hook store and use selectors to select the required slices:
// src/components/CounterDisplay.tsx
import { useCounterStore } from "../stores/useCounterStore";
export default function CounterDisplay() {
// Select state count using a selector function
const count = useCounterStore((state) => state.count);
return (
<div className="p-6 border rounded shadow-sm text-center">
<h2 className="text-xl font-bold">Counter Status</h2>
<p className="text-3xl mt-2">{count}</p>
</div>
);
}3. Invoking Updater Actions
In a separate component, you can import and trigger actions to update the state. The rest of the store will update and trigger re-renders instantly:
// src/components/CounterControls.tsx
import { useCounterStore } from "../stores/useCounterStore";
export default function CounterControls() {
const increment = useCounterStore((state) => state.increment);
const decrement = useCounterStore((state) => state.decrement);
return (
<div className="flex gap-4 p-4 justify-center">
<button onClick={decrement} className="bg-red-500 text-white px-4 py-2 rounded">
Decrease
</button>
<button onClick={increment} className="bg-green-500 text-white px-4 py-2 rounded">
Increase
</button>
</div>
);
}Published on Last updated: