Sub topic 14
Organizing large stores with slices
This chapter assumes you can already create a store with create, read it with selectors, and write actions with set. It also assumes you know the create<T>()(...) TypeScript form from the typing chapter. Middleware appears near the end, so it helps to have seen devtools and persist.
Why a single store file stops scaling
A store with three fields is easy to read. A store with forty fields and twenty actions in one create call is not. The actions for unrelated features sit next to each other, and the TypeScript interface grows without limit. Several people editing the same file will also produce merge conflicts.
You have two ways to split it:
- Several separate stores, one per feature.
- One store built from several slices. A slice is a function that creates one part of the state, with the actions that belong to it. The store spreads all the slices into a single object.
This chapter covers the second approach. Both are valid, and the last section compares them.
The shape of a slice
A slice is a state creator. It receives the same set, get and api arguments that create passes to your function, and it returns a plain object. Each slice is typed against the type of the whole store, so it can later reach into other slices.
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),
}))StateCreator takes four type parameters. For now, read them as follows:
| Position | Value above | Meaning |
|---|---|---|
| 1 | `AllSlices` | The type of the full store. `set` and `get` use it. |
| 2 | `[]` | Middleware mutators applied to the store, as input. |
| 3 | `[]` | Middleware mutators this creator adds. |
| 4 | `BearSlice` | The type this function returns. |
The combined store passes ...args to each slice. Those arguments are the single set, get and api of the one store. Because all slices share them, a set call in the bear slice changes the same state object that the fish slice reads.
How the pieces fit together
After the merge, the store is one flat object. Components cannot tell which slice a field came from. They read it like any other field.
Reading slices in components
Selectors work as before, so a component reads only the part it needs.
import { useBoundStore } from './boundStore'
function BearCounter() {
const bears = useBoundStore((state) => state.bears)
return <h1>{bears} bears around here</h1>
}
function FishControls() {
const fishes = useBoundStore((state) => state.fishes)
const addFish = useBoundStore((state) => state.addFish)
return <button onClick={addFish}>{fishes} fishes. Add one</button>
}Slices organize your code. They do not isolate re-renders. BearCounter re-renders only when bears changes because of its selector, not because it is "in the bear slice".
Actions that touch more than one slice
Slices become more useful when one action needs data from another slice. Use get for this. get returns the current state of the whole store, so it can call or read anything.
import { create, StateCreator } from 'zustand'
interface BearSlice {
bears: number
addBear: () => void
}
interface FishSlice {
fishes: number
addFish: () => void
}
interface SharedSlice {
addBoth: () => void
total: () => number
}
type AllSlices = BearSlice & FishSlice & SharedSlice
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 })),
})
const createSharedSlice: StateCreator<AllSlices, [], [], SharedSlice> = (
_set,
get,
) => ({
addBoth: () => {
get().addBear()
get().addFish()
},
total: () => get().bears + get().fishes,
})
export const useBoundStore = create<AllSlices>()((...args) => ({
...createBearSlice(...args),
...createFishSlice(...args),
...createSharedSlice(...args),
}))This is why every slice is typed with AllSlices as its first parameter. If createSharedSlice were typed against SharedSlice alone, get().addBear would be a type error.
Note that total is a function, not a stored number. Storing total as a field would mean updating it in every action that changes bears or fishes. This is the same derived-state advice from earlier in the tutorial.
Applying middleware to a sliced store
Apply middleware once, around the combined creator, not inside each slice. Wrapping each slice would create several persisted or traced stores instead of one.
import { create, StateCreator } from 'zustand'
import { devtools } from 'zustand/middleware'
interface BearSlice {
bears: number
addBear: () => void
}
interface FishSlice {
fishes: number
addFish: () => void
}
type AllSlices = BearSlice & FishSlice
const createBearSlice: StateCreator<
AllSlices,
[['zustand/devtools', never]],
[],
BearSlice
> = (set) => ({
bears: 0,
addBear: () =>
set((state) => ({ bears: state.bears + 1 }), undefined, 'bears/add'),
})
const createFishSlice: StateCreator<
AllSlices,
[['zustand/devtools', never]],
[],
FishSlice
> = (set) => ({
fishes: 0,
addFish: () =>
set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fishes/add'),
})
export const useBoundStore = create<AllSlices>()(
devtools((...args) => ({
...createBearSlice(...args),
...createFishSlice(...args),
})),
)The second type parameter now lists ['zustand/devtools', never]. It tells TypeScript that set accepts the extra arguments devtools adds. Here the third argument is an action name that appears in Redux DevTools. Each middleware you add to the combined store needs a matching entry in this list, in the same order. With persist added, the list would also include ['zustand/persist', unknown].
Common mistakes with slices
- Wrapping each slice in middleware. Wrap the combined creator once.
- Forgetting to pass
...args. If you writecreateBearSlice(set)and later add a slice that needsget, it will break. Passing...argsalways forwards all three arguments. - Typing a slice against its own interface. Use the combined type as the first
StateCreatorparameter if the slice ever callsget()or reads other slices' state. - Expecting namespaces. State is flat.
state.bearsis correct, andstate.bear.countdoes not exist unless you build that nesting yourself. - Persisting everything. With
persist, usepartializeto save only the fields that should survive a reload. Functions are not serializable and are skipped anyway.
Slices or separate stores
| Situation | Better choice |
|---|---|
| Actions in one feature must read or write another feature's state | Slices in one store |
| One `devtools` timeline and one `persist` entry are wanted | Slices in one store |
| Features are independent and rarely interact | Separate stores |
| Different features need different persistence keys or storage | Separate stores |
| A feature may be removed or lazy-loaded | Separate stores |
Separate stores are the simpler default. Move to slices when cross-feature actions start to make several stores awkward.
Exercise
In the sliced store above, you add a reset action to createFishSlice that calls set({ fishes: 0, bears: 0 }). It type-checks and works. A teammate says this is a design smell. What is the problem, and how would you restructure it?
Show answer
The fish slice now changes state owned by the bear slice, so a change to the bear slice can break fish code. Give each slice its own reset, for example resetBears and resetFishes. Then add a shared slice with resetAll: () => { get().resetBears(); get().resetFishes() }. Each slice then manages only its own fields, and the shared slice holds the cross-slice behavior.
Exercise
You wrap createBearSlice and createFishSlice each in their own persist(...) call inside the combined create. What goes wrong, and where should persist go?
Show answer
Each persist wrapper manages its own storage key and rehydration, and only one of them can be the real store middleware. The result is confusing or broken persistence. Apply persist once around the combined state creator, like create<AllSlices>()(persist((...args) => ({ ...createBearSlice(...args), ...createFishSlice(...args) }), { name: 'bound-store' })). Use partialize to choose which fields are saved.