zustand/docs/guides/immutable-state-and-merging.md
Jacob Bergholtz 4ed81bc11b
Add usage with context to docs (#1291)
* docs: context guide proposal

* fix(docs): typo & omit comment

* fix(docs): remove horizontal rules

* fix(docs): add wiki link to DI

* fix(docs): format with prettier

* fix(docs): cases that model => where... is needed

* fix(docs): use sentence case

* fix(docs): omit quote block

* fix(docs): into "a" custom hook

* fix(docs): format with prettier

* fix(docs): sort broken nav indexes

* Update docs/guides/initialize-state-with-props.md

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>

* fix(docs): reintroduce React.createContext example

* scripts: escape quotes

* styles: run prettier

* fix(docs): omit 'React' from imports

* styles: run prettier

* styles: run prettier

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
2022-09-18 09:01:06 +09:00

60 lines
1.4 KiB
Markdown

---
title: Immutable state and merging
nav: 4
---
Like with React's `useState`, we need to update state immutably.
Here's a typical example:
```jsx
import 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:
```js
set((state) => ({ ...state, count: state.count + 1 }))
```
However, as this is a common pattern, `set` actually merges state, and
we can skip the `...state` part:
```js
set((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:
```jsx
import 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-nested-state-object-values.md).
## Replace flag
To disable the merging behavior, you can specify a `replace` boolean value for `set` like so:
```js
set((state) => newState, true)
```