Actions Inside the Store
What you'll learn: How to define methods inside your Zustand store that encapsulate state updates, keeping your logic organized and colocated with your data.
The Problem with Scattered Logic
You could call set() directly in your components whenever you need to update state. But as your app grows, you'd end up with state update logic scattered everywhere. If the logic for updating a counter lives in five different components, good luck changing it consistently later.
Actions: Methods That Live with State
Actions are functions you define inside your store that call set() internally. They encapsulate the "how" of updating state, right next to the "what" of your state shape.
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
user: null,
// Actions that update state
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
setUser: (user) => set({ user }),
clearUser: () => set({ user: null }),
}));
Now your components just call increment() or setUser(userData) — they don't need to know how state updates work.
function Counter() {
const increment = useStore((state) => state.increment);
return <button onClick={increment}>+1</button>;
}
Why This Matters
This pattern gives you a single source of truth for state logic. Need to add logging? Validation? You change it once, in the action. Your components stay clean and declarative — they just trigger actions and react to state changes.
Key Takeaway: Define actions as methods inside your Zustand store to keep state update logic colocated with state data, making your code easier to maintain and reason about.