Skip to content
Myr

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 file

Take it

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

lines 1–59why, one step back
1---
2title: Immutable state and merging3nav: 74---56Like with React's `useState`, we need to update state immutably.78Here's a typical example:910```jsx11import { create } from 'zustand'1213const useCountStore = create((set) => ({14 count: 0,15 inc: () => set((state) => ({ count: state.count + 1 })),16}))17```1819The `set` function is to update state in the store.20Because the state is immutable, it should have been like this:2122```js23set((state) => ({ ...state, count: state.count + 1 }))24```2526However, as this is a common pattern, `set` actually merges state, and27we can skip the `...state` part:2829```js30set((state) => ({ count: state.count + 1 }))31```3233## Nested objects3435The `set` function merges state at only one level.36If you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:3738```jsx39import { create } from 'zustand'4041const useCountStore = create((set) => ({42 nested: { count: 0 },43 inc: () =>44 set((state) => ({45 nested: { ...state.nested, count: state.nested.count + 1 },46 })),47}))48```4950For complex use cases, consider using some libraries that help with immutable updates.51You can refer to [Updating nested state object values](./updating-state.md#deeply-nested-object).5253## Replace flag5455To disable the merging behavior, you can specify a `replace` boolean value for `set` like so:5657```js58set((state) => newState, true)59```