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

1.4 KiB

title nav
Immutable state and merging 4

Like with React's useState, we need to update state immutably.

Here's a typical example:

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:

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:

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:

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.

Replace flag

To disable the merging behavior, you can specify a replace boolean value for set like so:

set((state) => newState, true)