immutable-state-and-merging.md
This file
Path
docs/learn/guides/immutable-state-and-merging.md
59 lines · 1.4 KiB · Markdown
Last changed by
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960---title: Immutable state and mergingnav: 7---
Like with React's `useState`, we need to update state immutably.
Here's a typical example:
```jsximport { create } from 'zustand'
const useCountStore = create((set) => ({ count: 0, inc: () => set((state) => ({ count: state.count + 1 })),}))```
The `set` function is to update state in the store.Because the state is immutable, it should have been like this:
```jsset((state) => ({ ...state, count: state.count + 1 }))```
However, as this is a common pattern, `set` actually merges state, andwe can skip the `...state` part:
```jsset((state) => ({ count: state.count + 1 }))```
## Nested objects
The `set` function merges state at only one level.If you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:
```jsximport { create } from 'zustand'
const useCountStore = create((set) => ({ nested: { count: 0 }, inc: () => set((state) => ({ nested: { ...state.nested, count: state.nested.count + 1 }, })),}))```
For complex use cases, consider using some libraries that help with immutable updates.You can refer to [Updating nested state object values](./updating-state.md#deeply-nested-object).
## Replace flag
To disable the merging behavior, you can specify a `replace` boolean value for `set` like so:
```jsset((state) => newState, true)```