Multi-Store
Problem
A monolithic store becomes an unmaintainable mess as the application grows. Unrelated state changes trigger re-renders across the entire app. Team members conflict when editing the same massive state file. Authentication state, UI state, and business data are tangled together, making it hard to reason about each domain independently.
Solution
Separate state into multiple stores organized by domain or feature. This creates clear boundaries and prevents a single monolithic store from becoming unwieldy.
Example
This example shows two independent stores for different domains (user authentication and shopping cart), keeping concerns separated and preventing unnecessary coupling.
// User authentication store - handles auth state separately
const userStore = create((set) => ({
user: null,
// Update only user-related state
login: (user) => set({ user })
}));
// Shopping cart store - handles cart state independently
const cartStore = create((set) => ({
items: [],
// Update only cart-related state
addItem: (item) => set((state) => ({
items: [...state.items, item]
}))
}));
Benefits
- Creates clear boundaries between different domains and features.
- Reduces re-renders by isolating updates to specific stores.
- Makes code easier to understand by separating concerns.
- Enables teams to work independently on different state domains.
Tradeoffs
- Can make coordinating state across stores more complex.
- May lead to duplication if shared state isn’t properly extracted.
- Requires planning to determine appropriate store boundaries.
- Can make it harder to debug when state is scattered across multiple stores.