Skip to content

Commit

Permalink
fix(readme): description with createWithEqualityFn (#1985)
Browse files Browse the repository at this point in the history
* fix(readme): description with createWithEqualityFn

* fix wording

---------

Co-authored-by: Blazej Sewera <code@sewera.dev>
  • Loading branch information
dai-shi and sewera authored Aug 12, 2023
1 parent 0426978 commit 49d43b7
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,22 @@ const honey = useBearStore((state) => state.honey)

If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing the `shallow` equality function.

To use a custom equality function, you need `createWithEqualityFn` instead of `create`. Usually you want to specify `Object.is` as the second argument for the default equality function, but it's configurable.

```jsx
import { createWithEqualityFn } from 'zustand/traditional'
import { shallow } from 'zustand/shallow'

// Use createWithEqualityFn instead of create
const useBearStore = createWithEqualityFn(
(set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}),
Object.is // Specify the default equality function, which can be shallow
)

// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useBearStore(
(state) => ({ nuts: state.nuts, honey: state.honey }),
Expand Down

1 comment on commit 49d43b7

@vercel
Copy link

@vercel vercel bot commented on 49d43b7 Aug 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.