mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
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:
parent
1dd85fe24d
commit
e489a63513
@ -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.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user