fix(docs): improve v5 migration guide (#2749)

* fix(docs): improve v5 migration guide

* Update docs/migrations/migrating-to-v5.md

Co-authored-by: Blazej Sewera <code@sewera.dev>

---------

Co-authored-by: Blazej Sewera <code@sewera.dev>
This commit is contained in:
Daishi Kato 2024-09-22 00:07:52 +09:00 committed by GitHub
parent 18c0a3d97d
commit f82f56ddeb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -98,9 +98,10 @@ For example, this may cause infinite loops.
```js
// v4
const action = useMainStore((state) => {
return state.action ?? () => {}
})
const [searchValue, setSearchValue] = useStore((state) => [
state.searchValue,
state.setSearchValue,
])
```
The error message will be something like this:
@ -109,6 +110,26 @@ The error message will be something like this:
Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
```
To fix it, use the `useShallow` hook, which will return a stable reference.
```js
// v5
import { useShallow } from 'zustand/shallow'
const [searchValue, setSearchValue] = useStore(
useShallow((state) => [state.searchValue, state.setSearchValue]),
)
```
Here's another example that may cause infinite loops.
```js
// v4
const action = useMainStore((state) => {
return state.action ?? () => {}
})
```
To fix it, make sure the selector function returns a stable reference.
```js