zustand/docs/guides/updating-nested-state-object-values.md
Fawaz Haroun 476a381df8
fix(docs): Issue 1120 docs guides (#1244)
* docs: testing documentation review

* docs: auto-generated-selectors documentation review

* docs: auto-generated-selectors documentation review

* docs: flux-inspired-practices documentation review

* docs: flux-inspired-practices documentation review

* docs: flux-inspired-practices documentation review

* docs: immutable-state-and-merging documentation review

* docs: immutable-state-and-merging documentation review

* docs: event-handler-in-pre-react-18 documentation review

* docs: ran the yarn run prettier command

* review: reviewed documentation guides

* review: typo fixes and ran yarn run prettier

* review: change based on review comment

* review: change based on review comment

* review: change based on review comment
2022-08-31 08:09:15 +09:00

1.6 KiB

title nav
Updating nested state object values 4

Deeply nested object

If you have a deep state object like this:

type State = {
  deep: {
    nested: {
      obj: { count: number }
    }
  }
}

It requires some effort to update the count value immutably.

Normal approach

The normal approach is to copy state object with the spread operator ... like so:

  normalInc: () =>
    set((state) => ({
      deep: {
        ...state.deep,
        nested: {
          ...state.deep.nested,
          obj: {
            ...state.deep.nested.obj,
            count: state.deep.nested.obj.count + 1
          }
        }
      }
    })),

This is very long!

With immer

Many people use immer to update nested values. You can use immer to shorten your state updates for deeply nested object like this:

  immerInc: () =>
    set(produce((state: State) => { ++state.deep.nested.obj.count })),

What a reduction!

With optics-ts

There is another option with optics-ts:

  opticsInc: () =>
    set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),

Unlike immer, optics-ts does not use proxies or mutation syntax.

With ramda

You can also use ramda:

  ramdaInc: () =>
    set(R.over(R.lensPath(["deep", "nested", "obj", "count"]), (c) => c + 1)),

Both ramda and optics-ts also work with types.

CodeSandbox Demo

https://codesandbox.io/s/zustand-normal-immer-optics-ramda-updating-ynn3o?file=/src/App.tsx