-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathmigrating-to-v5.md
238 lines (181 loc) · 5.56 KB
/
migrating-to-v5.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
---
title: 'How to Migrate to v5 from v4'
nav: 23
---
# How to Migrate to v5 from v4
We highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.
## Changes in v5
- Drop default exports
- Drop deprecated features
- Make React 18 the minimum required version
- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)
- Make TypeScript 4.5 the minimum required version
- Drop UMD/SystemJS support
- Organize entry points in the package.json
- Drop ES5 support
- Stricter types when setState's replace flag is set
- Persist middleware behavioral change
- Other small improvements (technically breaking changes)
## Migration Guide
### Using custom equality functions such as `shallow`
The `create` function in v5 does not support customizing equality function.
If you use custom equality function such as `shallow`,
the easiest migration is to use `createWithEqualityFn`.
```js
// v4
import { create } from 'zustand'
import { shallow } from 'zustand/shallow'
const useCountStore = create((set) => ({
count: 0,
text: 'hello',
// ...
}))
const Component = () => {
const { count, text } = useCountStore(
(state) => ({
count: state.count,
text: state.text,
}),
shallow,
)
// ...
}
```
That can be done with `createWithEqualityFn` in v5:
```bash
npm install use-sync-external-store
```
```js
// v5
import { createWithEqualityFn as create } from 'zustand/traditional'
// The rest is the same as v4
```
Alternatively, for the `shallow` use case, you can use `useShallow` hook:
```js
// v5
import { create } from 'zustand'
import { useShallow } from 'zustand/shallow'
const useCountStore = create((set) => ({
count: 0,
text: 'hello',
// ...
}))
const Component = () => {
const { count, text } = useCountStore(
useShallow((state) => ({
count: state.count,
text: state.text,
})),
)
// ...
}
```
### Requiring stable selector outputs
There is a behavioral change in v5 to match React default behavior.
If a selector returns a new reference, it may cause infinite loops.
For example, this may cause infinite loops.
```js
// v4
const [searchValue, setSearchValue] = useStore((state) => [
state.searchValue,
state.setSearchValue,
])
```
The error message will be something like this:
```plaintext
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
// v5
const FALLBACK_ACTION = () => {}
const action = useMainStore((state) => {
return state.action ?? FALLBACK_ACTION
})
```
Alternatively, if you need v4 behavior, `createWithEqualityFn` will do.
```js
// v5
import { createWithEqualityFn as create } from 'zustand/traditional'
```
### Stricter types when setState's replace flag is set (Typescript only)
```diff
- setState:
- (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined) => void;
+ setState:
+ (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: false) => void;
+ (state: T | ((state: T) => T), replace: true) => void;
```
If you are not using the `replace` flag, no migration is required.
If you are using the `replace` flag and it's set to `true`, you must provide a complete state object.
This change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.
**Examples:**
```ts
// Partial state update (valid)
store.setState({ key: 'value' })
// Complete state replacement (valid)
store.setState({ key: 'value' }, true)
// Incomplete state replacement (invalid)
store.setState({}, true) // Error
```
#### Handling Dynamic `replace` Flag
If the value of the `replace` flag is dynamic and determined at runtime, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with `as any`:
```ts
const replaceFlag = Math.random() > 0.5
store.setState(partialOrFull, replaceFlag as any)
```
#### Persist middlware no longer stores item at store creation
Previously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).
For example, in the following code, the initial state is stored in the storage.
```js
// v4
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
const useCountStore = create(
persist(
() => ({
count: Math.floor(Math.random() * 1000),
}),
{
name: 'count',
},
),
)
```
In v5, this is no longer the case, and you need to explicitly set the state after store creation.
```js
// v5
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
const useCountStore = create(
persist(
() => ({
count: 0,
}),
{
name: 'count',
},
),
)
useCountStore.setState({
count: Math.floor(Math.random() * 1000),
})
```
## Links
- https://github.com/pmndrs/zustand/pull/2138
- https://github.com/pmndrs/zustand/pull/2580