Course contentsShow
← React
Lesson 1717 of 2,39641. State Management EcosystemFree lesson

Multiple Stores and When to Split

Creating separate stores for unrelated domains versus keeping everything in one place.

Multiple Stores and When to Split

You'll learn how to decide whether to split your Zustand state into multiple stores or keep everything in one place.

The Default: One Store Per Domain

With Zustand's lightweight approach, you're not forced into a single global store like in Redux. You can create multiple independent stores, each handling a separate domain of your application. Think of stores like departments in a company—accounting doesn't need to know about HR's internal data.

When to Split Into Multiple Stores

Create separate stores when state domains are truly independent:

// userStore.js - Authentication and user profile
export const useUserStore = create((set) => ({
  user: null,
  login: (user) => set({ user }),
  logout: () => set({ user: null })
}));

// cartStore.js - Shopping cart logic
export const useCartStore = create((set) => ({
  items: [],
  addItem: (item) => set((state) => ({ 
    items: [...state.items, item] 
  }))
}));

// themeStore.js - UI preferences
export const useThemeStore = create((set) => ({
  mode: 'light',
  toggleTheme: () => set((state) => ({ 
    mode: state.mode === 'light' ? 'dark' : 'light' 
  }))
}));

Benefits of splitting:

  • Performance: Components only subscribe to relevant stores
  • Code organization: Easier to locate and maintain domain logic
  • Bundle splitting: Stores can be lazy-loaded with their features
  • Testing: Isolated stores are simpler to test

When to Keep One Store

Keep everything together when state domains frequently interact:

// Single store when checkout needs user + cart
export const useStore = create((set) => ({
  user: null,
  cart: [],
  checkout: () => set((state) => {
    // Needs both user and cart data
    if (!state.user) return state;
    // Process checkout logic...
  })
}));

Key Takeaway: Split stores by domain boundaries (user, cart, UI), but keep them together if they're tightly coupled—prioritize organization and performance over dogmatic separation.