The Slices Pattern: Scaling Large Stores
In small applications, keeping all states inside a single store file is fine. However, in larger projects, a single store can quickly grow to thousands of lines. Zustand addresses this using the Slices Pattern.
1. What is the Slices Pattern?
The Slices Pattern allows you to split your global store into separate files (slices) while maintaining a single unified store under the hood.
This gives you:
- Highly organized, maintainable code structures.
- Complete access to other slice actions and states.
2. Implementing Slices
Let us build a global store composed of two slices: createAuthSlice and createCartSlice.
Step A: Define the Auth Slice
// src/stores/createAuthSlice.ts
import { StateCreator } from "zustand";
export interface AuthSlice {
username: string;
loginUser: (name: string) => void;
}
export const createAuthSlice: StateCreator<AuthSlice, [], [], AuthSlice> = (set) => ({
username: "",
loginUser: (name) => set({ username: name }),
});Step B: Define the Cart Slice
// src/stores/createCartSlice.ts
import { StateCreator } from "zustand";
export interface CartSlice {
itemsCount: number;
addItem: () => void;
}
export const createCartSlice: StateCreator<CartSlice, [], [], CartSlice> = (set) => ({
itemsCount: 0,
addItem: () => set((state) => ({ itemsCount: state.itemsCount + 1 })),
});3. Composing the Slices into a Single Store
Finally, import the separate slices and combine them inside your root store file using the create function:
// src/stores/useRootStore.ts
import { create } from "zustand";
import { createAuthSlice, AuthSlice } from "./createAuthSlice";
import { createCartSlice, CartSlice } from "./createCartSlice";
// Compose combined TypeScript interface
type RootStore = AuthSlice & CartSlice;
export const useRootStore = create<RootStore>((...a) => ({
...createAuthSlice(...a),
...createCartSlice(...a),
}));Now, you can consume any state or action from the combined store inside your React components using a single unified hook:
import { useRootStore } from "../stores/useRootStore";
function Header() {
const username = useRootStore((state) => state.username);
const itemsCount = useRootStore((state) => state.itemsCount);
const addItem = useRootStore((state) => state.addItem);
}Published on Last updated: