codez.guru

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) =&gt; ({
  isOpen: false,
  toggle: () =&gt; set((state) =&gt; ({ isOpen: !state.isOpen })),
}));

You can now use:

const isOpen = useToggleStore((s) =&gt; s.isOpen);
const toggle = useToggleStore((s) =&gt; s.toggle);

Implementing a Counter Store

Counter patterns are ideal for understanding state mutation:

type CounterStore = {
  count: number;
  inc: () =&gt; void;
  dec: () =&gt; void;
  reset: () =&gt; void;
};

const useCounterStore = create<counterstore>((set) =&gt; ({
  count: 0,
  inc: () =&gt; set((s) =&gt; ({ count: s.count + 1 })),
  dec: () =&gt; set((s) =&gt; ({ count: s.count - 1 })),
  reset: () =&gt; 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&lt;{ name: string; age: number }&gt;) =&gt; void;
};

const useProfileStore = create<profilestore>((set) =&gt; ({
  profile: { name: "", age: 0 },
  updateProfile: (partial) =&gt;
    set((state) =&gt; ({
      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, reset for better clarity

Next: Lesson 06 – Derived State and Computed Values