codez.guru

On this Page

  • Why UI State Belongs in Zustand
  • Managing Modals Globally
  • Sidebar and Drawer State
  • Theme Toggle and Dark Mode
  • Best Practices for Global UI Stores

On this Guide

  • Lesson 18: Zustand for Authentication and Session Management
  • Lesson 19: Managing Forms and Multi-Step Wizards with Zustand
  • Lesson 20: Undo/Redo Functionality with State Snapshots
  • Lesson 21: Zustand for App-Wide UI State (Modals, Sidebars, Themes)
  • Lesson 22: Combining Zustand with React Query for Async Data
  • Lesson 23: Real-Time Data Sync with WebSockets and Zustand
  • Lesson 24: Storing User Preferences and Settings
  • Lesson 25: Migrating from Redux or Context to Zustand

Why UI State Belongs in Zustand

Zustand is great for global UI state because:

  • πŸ“¦ No Provider is needed
  • 🎯 Easy to share state across layout and nested components
  • πŸ’‘ Works well with modals, sidebars, themes, tooltips, etc.

Managing Modals Globally

type ModalStore = {
  isOpen: boolean;
  openModal: () => void;
  closeModal: () => void;
};

export const useModalStore = create<modalstore>((set) =&gt; ({
  isOpen: false,
  openModal: () =&gt; set({ isOpen: true }),
  closeModal: () =&gt; set({ isOpen: false }),
}));

In your modal component:

const isOpen = useModalStore((s) =&gt; s.isOpen);
const closeModal = useModalStore((s) =&gt; s.closeModal);

{
  isOpen &amp;&amp; <modal onclose="{closeModal}"></modal>;
}

Trigger globally:

useModalStore.getState().openModal();

Sidebar and Drawer State

type SidebarStore = {
  visible: boolean;
  toggle: () =&gt; void;
};

export const useSidebarStore = create<sidebarstore>((set) =&gt; ({
  visible: false,
  toggle: () =&gt; set((s) =&gt; ({ visible: !s.visible })),
}));

Works with a layout component or navbar button.


Theme Toggle and Dark Mode

type ThemeStore = {
  darkMode: boolean;
  toggleTheme: () =&gt; void;
};

export const useThemeStore = create<themestore>((set) =&gt; ({
  darkMode: false,
  toggleTheme: () =&gt; set((s) =&gt; ({ darkMode: !s.darkMode })),
}));

Update document.body.classList in useEffect:

const darkMode = useThemeStore((s) =&gt; s.darkMode);

useEffect(() =&gt; {
  document.body.classList.toggle("dark", darkMode);
}, [darkMode]);

Best Practices for Global UI Stores

βœ… One store per feature (e.g., useModalStore, useThemeStore)
βœ… Avoid overloading one giant store with all UI
βœ… Persist theme preference if needed
βœ… Don’t use Zustand for transient component-local UI


Summary

  • Zustand is perfect for modals, sidebars, and themes
  • Share state between layout and deeply nested components
  • Keep stores focused and isolated by UI concern
  • Avoid context hell for simple UI toggles

Next: Lesson 22 – Combining Zustand with React Query for Async Data