Updating state
Zustand merges the object you pass to set into the current state, one level deep. This guide
shows how to update flat state, and several ways to update deeply nested state: by hand with
spreads, or with Immer, optics-ts or Ramda.
Flat updates
Updating state with Zustand is simple! Call the provided set function with
the new state, and it will be shallowly merged with the existing state in the
store. Note: See the next section for nested state.
Deeply nested object
If you have a deep state object like this:
Updating nested state requires some effort to ensure the process is completed immutably.
Normal approach
Similar to React or Redux, the normal approach is to copy each level of the
state object. This is done with the spread operator ..., and by manually
merging that in with the new state values. Like so:
This is very long! Let's explore some alternatives that will make your life easier.
With Immer
Many people use Immer to update nested values. Immer can be used anytime you need to update nested state such as in React, Redux and of course, Zustand!
You can use Immer to shorten your state updates for deeply nested objects. Let's take a look at an example:
What a reduction! Please take note of the gotchas listed here.
With optics-ts
There is another option with optics-ts:
Unlike Immer, optics-ts doesn't use proxies or mutation syntax.
With Ramda
You can also use Ramda:
Both Ramda and optics-ts also work with types.
Demo
https://stackblitz.com/edit/vitejs-vite-j6bjdygu
See also
- Immutable state and merging: how
setmerges state. - Maps and sets usage: updating
MapandSetvalues. immer: the Immer middleware.