# Split a store into slices

Use slices when one application-wide store has grown into several features. Each slice defines its own state and actions, but all slices share one store's `set` and `get`. You can coordinate their actions and apply middleware once at the combined-store boundary.

This example starts from the project in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start). Zustand is already installed; no additional package is needed. The finished screen shows bear and fish counts, buttons for each feature, and a button that increments both counts.

## 1. Define typed slices

Add `src/slices.ts`. Use [`StateCreator`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#statecreator) to give each slice access to the combined state while restricting its return value to its own slice.

```ts title="src/slices.ts"
import type { StateCreator } from 'zustand'

export type BearSlice = {
  bears: number
  addBear: () => void
  eatFish: () => void
}

export type FishSlice = {
  fishes: number
  addFish: () => void
}

export type BoundState = BearSlice & FishSlice

export const createBearSlice: StateCreator<BoundState, [], [], BearSlice> =
  (set) => ({
    bears: 0,
    addBear: () => set((state) => ({ bears: state.bears + 1 })),
    eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),
  })

export const createFishSlice: StateCreator<BoundState, [], [], FishSlice> =
  (set) => ({
    fishes: 0,
    addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
  })
```

In `StateCreator<BoundState, [], [], BearSlice>`, the first parameter describes the state available to `set` and `get`; the fourth describes the object the creator returns. The two empty tuples describe middleware mutators entering and leaving the creator. These slices do not install middleware themselves.

`eatFish` belongs to the bear slice but updates `fishes` in the shared state. Each update shallowly merges its returned fields, preserving the other slice's state and actions. This action subtracts one without imposing a minimum; the component below disables its button when there are no fish.

## 2. Combine the slices and render them

Add `src/bound-store.ts`. Call [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) once, forwarding the same initializer arguments to both slices and spreading their returned objects into one state object.

```ts title="src/bound-store.ts"
import { create } from 'zustand'
import { createBearSlice, createFishSlice } from './slices'
import type { BoundState } from './slices'

export const useBoundStore = create<BoundState>()((...args) => ({
  ...createBearSlice(...args),
  ...createFishSlice(...args),
}))
```

The result is one bound store hook, not a separate store instance per slice. Add `src/SliceCounter.tsx` to consume its state and actions through selectors.

```tsx title="src/SliceCounter.tsx"
import { useBoundStore } from './bound-store'

export default function SliceCounter() {
  const bears = useBoundStore((state) => state.bears)
  const fishes = useBoundStore((state) => state.fishes)
  const addBear = useBoundStore((state) => state.addBear)
  const addFish = useBoundStore((state) => state.addFish)
  const eatFish = useBoundStore((state) => state.eatFish)

  return (
    <main style={{ minHeight: 400, display: 'grid', placeContent: 'center', gap: 16 }}>
      <h1>Bear and fish slices</h1>
      <p aria-live="polite">Bears: {bears} · Fishes: {fishes}</p>
      <button type="button" onClick={addBear}>Add a bear</button>
      <button type="button" onClick={addFish}>Add a fish</button>
      <button type="button" onClick={eatFish} disabled={fishes === 0}>
        Eat a fish
      </button>
    </main>
  )
}
```

Mount `SliceCounter` from `./SliceCounter.tsx` in place of the quick start's counter, following the [React quick start's entry-point setup](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start).

Run `npm run build`, then `npm run dev` and open Vite's local URL. Both counts start at zero. **Add a bear** increments only bears; **Add a fish** increments only fishes. After adding a fish, **Eat a fish** decrements fishes through the bear slice's action.

## Updating multiple stores

Although the features live in separate slice creators, they update the same store. Add a coordinating slice that calls existing actions through `get` when its action runs.

1. Add `src/shared-slice.ts`:

```ts title="src/shared-slice.ts"
import type { StateCreator } from 'zustand'
import type { BoundState } from './slices'

export type SharedSlice = {
  addBearAndFish: () => void
}

export const createSharedSlice: StateCreator<BoundState, [], [], SharedSlice> =
  (_set, get) => ({
    addBearAndFish: () => {
      get().addBear()
      get().addFish()
    },
  })
```

2. Add `src/shared-bound-store.ts` to include the shared slice:

```ts title="src/shared-bound-store.ts"
import { create } from 'zustand'
import { createBearSlice, createFishSlice } from './slices'
import type { BoundState } from './slices'
import { createSharedSlice } from './shared-slice'
import type { SharedSlice } from './shared-slice'

export const useBoundStore = create<BoundState & SharedSlice>()((...args) => ({
  ...createBearSlice(...args),
  ...createFishSlice(...args),
  ...createSharedSlice(...args),
}))
```

3. Update `src/SliceCounter.tsx` to select the coordinating action and bind it to another button:

```tsx title="src/SliceCounter.tsx"
import { useBoundStore } from './shared-bound-store'

export default function SliceCounter() {
  const bears = useBoundStore((state) => state.bears)
  const fishes = useBoundStore((state) => state.fishes)
  const addBear = useBoundStore((state) => state.addBear)
  const addFish = useBoundStore((state) => state.addFish)
  const eatFish = useBoundStore((state) => state.eatFish)
  const addBearAndFish = useBoundStore((state) => state.addBearAndFish)

  return (
    <main style={{ minHeight: 400, display: 'grid', placeContent: 'center', gap: 16 }}>
      <h1>Bear and fish slices</h1>
      <p aria-live="polite">Bears: {bears} · Fishes: {fishes}</p>
      <button type="button" onClick={addBear}>Add a bear</button>
      <button type="button" onClick={addFish}>Add a fish</button>
      <button type="button" onClick={eatFish} disabled={fishes === 0}>
        Eat a fish
      </button>
      <button type="button" onClick={addBearAndFish}>Add a bear and a fish</button>
    </main>
  )
}
```

Click **Add a bear and a fish** to increase each displayed count by one. The coordinating action reuses both feature actions; it does not duplicate their update logic. The calls make two state updates, not one atomic update: store subscribers receive a notification for each `set` call. If you need one notification, update both fields in a single `set` updater instead.

For action initialization and organization, see [Organize store actions](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/organize-store-actions).

## Adding middlewares

Wrap the combined initializer with [`persist`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#persist) to store both feature counts under one storage key.

1. Change `src/shared-bound-store.ts` to the following. Leave the slice creators and mounted component in place.

```ts title="src/shared-bound-store.ts"
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { createBearSlice, createFishSlice } from './slices'
import type { BoundState } from './slices'
import { createSharedSlice } from './shared-slice'
import type { SharedSlice } from './shared-slice'

export const useBoundStore = create<BoundState & SharedSlice>()(
  persist(
    (...args) => ({
      ...createBearSlice(...args),
      ...createFishSlice(...args),
      ...createSharedSlice(...args),
    }),
    {
      name: 'bear-fish-slices',
      version: 1,
      partialize: (state) => ({ bears: state.bears, fishes: state.fishes }),
    },
  ),
)
```

2. Build and run again. Add bears and fish, then reload the page on the same origin. The counts return from browser `localStorage`; the actions come from the slice creators. On a fresh storage key, both counts start at zero.

`persist` writes a versioned state envelope after updates and hydrates once when the store initializes. `partialize` stores only the two counts, and hydration merges them into the initial state containing the actions. Do not add a second loader or a manual restore call for this example.

### Options that matter here

| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| `name` | `string` | Required | Chooses the unique storage key for the combined store. |
| `partialize` | Function from store state to persisted state | Identity function | Selects the fields written to storage; here, both counts. |
| `version` | `number` | `0` | Tags saved state. A mismatched version is not loaded unless you supply a migration. |

For storage selection and persistence controls, continue with [Persist store state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/persist-store-state). For changing the saved shape, use [Migrate persisted data](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/migrate-persisted-data).

## Keep middleware at the boundary

Apply middleware to the combined store, not individual slices, so every feature uses the same wrapped store. This example's `persist` wrapper forwards the normal `set` and `get` calls to the plain slice creators while saving their updates.

When middleware changes the types available inside a slice, describe its incoming mutators in the second `StateCreator` parameter. For example, a slice under [`devtools`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand-middleware#devtools) uses `StateCreator<BoundState, [['zustand/devtools', never]], [], BearSlice>`.

Put `devtools` outermost when composing middleware. With Immer, the order is `devtools(immer(...))`, not `immer(devtools(...))`: this preserves the additional `setState` type parameter that `devtools` supplies. See [Update state with Immer](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/update-state-with-immer) for Immer updates and [Write typed middleware](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/write-typed-middleware) for mutator typing.

## Related

- [Organize store actions](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/organize-store-actions) covers colocated actions and calling one action from another.
- [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) develops the store and selector types used here.
- Explore the [live Zustand demo](https://zustand-demo.pmnd.rs/) for a running store hook driving React UI.
