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 ( +
+

Number of bears: {bears}

+

Number of fishes: {fishes}

+ +
+ ) +} + +export default App +``` + +## Adding middlewares + +Adding middlewares to a combined store is the same as with other normal stores. + +Adding `persist` middleware to our `useBoundStore`: + +```js +import create from 'zustand' +import { createBearSlice } from './bearSlice' +import { createFishSlice } from './fishSlice' +import { persist } from 'zustand/middleware' + +export const useBoundStore = create( + persist( + (...a) => ({ + ...createBearSlice(...a), + ...createFishSlice(...a), + }), + { name: 'bound-store' } + ) +) +``` + +## Usage with TypeScript + +A detailed guide on how to use the slice pattern in Zustand with TypeScript can be found [here](./typescript.md#slices-pattern). diff --git a/docs/guides/typescript.md b/docs/guides/typescript.md index 39228e180c..e750b18111 100644 --- a/docs/guides/typescript.md +++ b/docs/guides/typescript.md @@ -406,6 +406,8 @@ const useBoundStore = create()((...a) => ({ })) ``` +A detailed explanation on the slices pattern can be found [here](./slices-pattern.md). + If you have some middlewares then replace `StateCreator` with `StateCreator`. For example, if you are using `devtools` then it will be `StateCreator`. See the ["Middlewares and their mutators reference"](#middlewares-and-their-mutators-reference) section for a list of all mutators. ## Middlewares and their mutators reference