Don't recommend memoizing selectors (#1707)

As per the discussions below, memoizing selectors does not improve performance
significantly as of v4. Thus we should avoid recommending selector memoization.
Note that the same paragraph was removed from the README in PR #550
(https://github.com/pmndrs/zustand/pull/550)
and this section may have been left behind as an oversight.

- https://github.com/pmndrs/zustand/discussions/658
- https://github.com/pmndrs/zustand/discussions/971
This commit is contained in:
Yehyoung Kang 2023-03-22 18:09:14 +09:00 committed by GitHub
parent 1dd85fe24d
commit e489a63513
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -65,29 +65,6 @@ const currentBear = useCredentialsStore((state) => state.currentBear)
const bear = useBearStore((state) => state.bears[currentBear])
```
## Memoizing selectors
It is generally recommended to memoize selectors with `useCallback`.
This will prevent unnecessary computations each render.
It also allows React to optimize performance in concurrent mode.
```jsx
const fruit = useStore(useCallback((state) => state.fruits[id], [id]))
```
If a selector doesn't depend on scope,
you can define it outside the render function
to obtain a fixed reference without `useCallback`.
```jsx
const selector = (state) => state.berries
function Component() {
const berries = useStore(selector)
// ...
}
```
## Overwriting state
The `set` function has a second argument, `false` by default.