On this Page
- Managing Booleans with Toggle Actions
- Implementing a Counter Store
- Handling Small Object Updates
- Using Partial Set Updates
On this Guide
- Lesson 01: Introduction to Zustand and Store Basics
- Lesson 02: Creating Your First Store with TypeScript
- Lesson 03: Reading and Updating State in React Components
- Lesson 04: Selectors and Optimizing Renders
- Lesson 05: Handling Booleans, Counters, and Simple Objects
- Lesson 06: Derived State and Computed Values
- Lesson 07: Type Inference and store typing best practices
- Lesson 08: Custom Hooks and Reusable State Accessors
Managing Booleans with Toggle Actions
Toggles are a common UI need β dark mode, modals, sidebars, etc.
type ToggleStore = {
isOpen: boolean;
toggle: () => void;
};
const useToggleStore = create<togglestore>((set) => ({
isOpen: false,
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
}));
You can now use:
const isOpen = useToggleStore((s) => s.isOpen);
const toggle = useToggleStore((s) => s.toggle);
Implementing a Counter Store
Counter patterns are ideal for understanding state mutation:
type CounterStore = {
count: number;
inc: () => void;
dec: () => void;
reset: () => void;
};
const useCounterStore = create<counterstore>((set) => ({
count: 0,
inc: () => set((s) => ({ count: s.count + 1 })),
dec: () => set((s) => ({ count: s.count - 1 })),
reset: () => set({ count: 0 }),
}));
This pattern is fully reactive and easy to wire to UI buttons.
Handling Small Object Updates
You can store simple object state like this:
type ProfileStore = {
profile: {
name: string;
age: number;
};
updateProfile: (partial: Partial<{ name: string; age: number }>) => void;
};
const useProfileStore = create<profilestore>((set) => ({
profile: { name: "", age: 0 },
updateProfile: (partial) =>
set((state) => ({
profile: { ...state.profile, ...partial },
})),
}));
useProfileStore.getState().updateProfile({ name: "Ziv" });
Using Partial Set Updates
When updating nested state, use spread operators to ensure shallow merges.
β οΈ Zustandβs set() does not deeply merge by default β you must do it manually or with Immer (later lesson).
Summary
- Toggle and counter stores are great for UI logic
- Always spread nested objects manually when updating state
- Use actions like
toggle,inc,resetfor better clarity
Next: Lesson 06 β Derived State and Computed Values