diff --git a/docs/guides/slices-pattern.md b/docs/guides/slices-pattern.md new file mode 100644 index 0000000000..e4d4467b1c --- /dev/null +++ b/docs/guides/slices-pattern.md @@ -0,0 +1,90 @@ +--- +title: Slices Pattern +nav: 15 +--- + +## Slicing the store into smaller stores + +Your store can become bigger and bigger and tougher to maintain as you add more features. + +You can divide your main store into smaller individual stores to achieve modularity. This is simple to accomplish in Zustand! + +The first individual store: + +```js +export const createFishSlice = (set) => ({ + fishes: 0, + addFish: () => set((state) => ({ fishes: state.fishes + 1 })), +}) +``` + +Another individual store: + +```js +export const createBearSlice = (set) => ({ + bears: 0, + addBear: () => set((state) => ({ bears: state.bears + 1 })), + eatFish: () => set((state) => ({ fishes: state.fishes - 1 })), +}) +``` + +You can now combine both the stores into **one bounded store**: + +```js +import create from 'zustand' +import { createBearSlice } from './bearSlice' +import { createFishSlice } from './fishSlice' + +export const useBoundStore = create((...a) => ({ + ...createBearSlice(...a), + ...createFishSlice(...a), +})) +``` + +### Usage in a React component + +```jsx +import { useBoundStore } from './stores/useBoundStore' + +function App() { + const bears = useBoundStore((state) => state.bears) + const fishes = useBoundStore((state) => state.fishes) + const addBear = useBoundStore((state) => state.addBear) + return ( +