Sub topic 14
Organizing large stores with slices
This chapter assumes you can write a basic Zustand store with create, read it with selectors, and type it with create<T>()(...). It also assumes you know how set merges partial state.
Why split a store
One store can grow to dozens of fields and actions. A single file then becomes hard to read and review. The slices pattern splits the store into several state creators. Each creator owns one part of the state. A single create call combines them.
Zustand has no special "slice" feature. A slice is a function that takes set, get and the store API, and returns an object. The pattern relies only on object spread.
Writing two slices
Each slice is typed as a StateCreator. Its four type parameters are the full store type, the middleware that wrap the store, the middleware this slice adds, and the slice's own type. The empty arrays mean no middleware.
import { create, StateCreator } from 'zustand'
interface BearSlice {
bears: number
addBear: () => void
}
interface FishSlice {
fishes: number
addFish: () => void
}
type AllSlices = BearSlice & FishSlice
const createBearSlice: StateCreator<AllSlices, [], [], BearSlice> = (set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
})
const createFishSlice: StateCreator<AllSlices, [], [], FishSlice> = (set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
})
export const useBoundStore = create<AllSlices>()((...args) => ({
...createBearSlice(...args),
...createFishSlice(...args),
}))The store passes ...args (set, get and the store API) to every slice. All slices therefore write to the same state object. The result is one store, not several.
Using the bound store
Components read the store the same way as before. Selectors still limit re-renders to the values each component selects.
import { useBoundStore } from './boundStore'
function Bears() {
const bears = useBoundStore((state) => state.bears)
return <p>Bears: {bears}</p>
}Slices that read each other
Because every slice receives set and get, a slice can read state owned by another slice. Typing the first parameter as AllSlices is what makes this type-check. For example, a fish slice action can call get().bears. Keep this to a minimum. Each cross-slice read couples two files, and that coupling is what slices are meant to reduce.
Common errors
- Duplicate keys. If two slices define the same field, the later spread silently overwrites the earlier one. Give each slice unique names.
- Wrong
StateCreatortype. Typing the first parameter as only the slice type means the slice cannot see other slices throughget. Use the combined type. - Middleware in the wrong place. With middleware, apply it once, around the combined creator, not inside each slice. Then the second and third
StateCreatorparameters must list the middleware, for example[['zustand/devtools', never]].
Exercise
Two slices both define a field named status, and both are spread into the same create call. What happens, and how do you avoid it?
Show answer
The slice spread last overwrites the status field from the earlier slice, with no error at runtime. Avoid it by giving each slice unique field names, for example bearStatus and fishStatus, or by nesting each slice's state under its own key.