Skip to content
Myr

migrating-to-v5.md

This file

Path

docs/reference/migrations/migrating-to-v5.md

241 lines · 5.7 KiB · Markdown

Last changed by

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

History of this file

Take it

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 1–241why, one step back
1---
2title: How to Migrate to v5 from v43nav: 374---56# How to Migrate to v5 from v478We highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.910## Changes in v51112- Drop default exports13- Drop deprecated features14- Make React 18 the minimum required version15- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)16- Make TypeScript 4.5 the minimum required version17- Drop UMD/SystemJS support18- Organize entry points in the package.json19- Drop ES5 support20- Stricter types when setState's replace flag is set21- Persist middleware behavioral change22- Other small improvements (technically breaking changes)2324## Migration Guide2526### Using custom equality functions such as `shallow`2728The `create` function in v5 does not support customizing equality function.2930If you use custom equality function such as `shallow`,31the easiest migration is to use `createWithEqualityFn`.3233```js34// v435import { create } from 'zustand'36import { shallow } from 'zustand/shallow'3738const useCountStore = create((set) => ({39 count: 0,40 text: 'hello',41 // ...42}))4344const Component = () => {45 const { count, text } = useCountStore(46 (state) => ({47 count: state.count,48 text: state.text,49 }),50 shallow,51 )52 // ...53}54```5556That can be done with `createWithEqualityFn` in v5:5758```bash59npm install use-sync-external-store60```6162```js63// v564import { createWithEqualityFn as create } from 'zustand/traditional'6566// The rest is the same as v467```6869Alternatively, for the `shallow` use case, you can use `useShallow` hook:7071```js72// v573import { create } from 'zustand'74import { useShallow } from 'zustand/shallow'7576const useCountStore = create((set) => ({77 count: 0,78 text: 'hello',79 // ...80}))8182const Component = () => {83 const { count, text } = useCountStore(84 useShallow((state) => ({85 count: state.count,86 text: state.text,87 })),88 )89 // ...90}91```9293### Requiring stable selector outputs9495There is a behavioral change in v5 to match React default behavior.96If a selector returns a new reference, it may cause infinite loops.9798For example, this may cause infinite loops.99100```js101// v4102const [searchValue, setSearchValue] = useStore((state) => [103 state.searchValue,104 state.setSearchValue,105])106```107108The error message will be something like this:109110```plaintext111Uncaught 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.112```113114To fix it, use the `useShallow` hook, which will return a stable reference.115116```js117// v5118import { useShallow } from 'zustand/shallow'119120const [searchValue, setSearchValue] = useStore(121 useShallow((state) => [state.searchValue, state.setSearchValue]),122)123```124125Here's another example that may cause infinite loops.126127```js128// v4129const action = useMainStore((state) => {130 return state.action ?? () => {}131})132```133134To fix it, make sure the selector function returns a stable reference.135136```js137// v5138139const FALLBACK_ACTION = () => {}140141const action = useMainStore((state) => {142 return state.action ?? FALLBACK_ACTION143})144```145146Alternatively, if you need v4 behavior, `createWithEqualityFn` will do.147148```js149// v5150import { createWithEqualityFn as create } from 'zustand/traditional'151```152153### Stricter types when setState's replace flag is set (Typescript only)154155```diff156- setState:157- (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: boolean | undefined) => void;158+ setState:159+ (partial: T | Partial<T> | ((state: T) => T | Partial<T>), replace?: false) => void;160+ (state: T | ((state: T) => T), replace: true) => void;161```162163If you are not using the `replace` flag, no migration is required.164165If you are using the `replace` flag and it's set to `true`, you must provide a complete state object.166This change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.167168**Examples:**169170```ts171// Partial state update (valid)172store.setState({ key: 'value' })173174// Complete state replacement (valid)175store.setState({ key: 'value' }, true)176177// Incomplete state replacement (invalid)178store.setState({}, true) // Error179```180181#### Handling Dynamic `replace` Flag182183If 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 the parameters of the `setState` function:184185```ts186const replaceFlag = Math.random() > 0.5187const args = [{ bears: 5 }, replaceFlag] as Parameters<188 typeof useBearStore.setState189>190store.setState(...args)191```192193#### Persist middleware no longer stores item at store creation194195Previously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).196197For example, in the following code, the initial state is stored in the storage.198199```js200// v4201import { create } from 'zustand'202import { persist } from 'zustand/middleware'203204const useCountStore = create(205 persist(206 () => ({207 count: Math.floor(Math.random() * 1000),208 }),209 {210 name: 'count',211 },212 ),213)214```215216In v5, this is no longer the case, and you need to explicitly set the state after store creation.217218```js219// v5220import { create } from 'zustand'221import { persist } from 'zustand/middleware'222223const useCountStore = create(224 persist(225 () => ({226 count: 0,227 }),228 {229 name: 'count',230 },231 ),232)233useCountStore.setState({234 count: Math.floor(Math.random() * 1000),235})236```237238## Links239240- https://github.com/pmndrs/zustand/pull/2138241- https://github.com/pmndrs/zustand/pull/2580