updating-state.md
This file
Path
docs/learn/guides/updating-state.md
141 lines · 3.3 KiB · Markdown
Last changed by
docs(updating-state): use curried create form with explicit state type (#3503)Seydi Charyyevbefore adoption038b938
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142---title: Updating statenav: 4---
## Flat updates
Updating state with Zustand is simple! Call the provided `set` function withthe new state, and it will be shallowly merged with the existing state in thestore. **Note** See next section for nested state.
```tsximport { create } from 'zustand'
type State = { firstName: string lastName: string}
type Action = { updateFirstName: (firstName: State['firstName']) => void updateLastName: (lastName: State['lastName']) => void}
// Create your store, which includes both state and (optionally) actionsconst usePersonStore = create<State & Action>()((set) => ({ firstName: '', lastName: '', updateFirstName: (firstName) => set(() => ({ firstName: firstName })), updateLastName: (lastName) => set(() => ({ lastName: lastName })),}))
// In consuming appfunction App() { // "select" the needed state and actions, in this case, the firstName value // and the action updateFirstName const firstName = usePersonStore((state) => state.firstName) const updateFirstName = usePersonStore((state) => state.updateFirstName)
return ( <main> <label> First name <input // Update the "firstName" state onChange={(e) => updateFirstName(e.currentTarget.value)} value={firstName} /> </label>
<p> Hello, <strong>{firstName}!</strong> </p> </main> )}```
## Deeply nested object
If you have a deep state object like this:
```tstype State = { deep: { nested: { obj: { count: number } } }}```
Updating nested state requires some effort to ensure the process is completedimmutably.
### Normal approach
Similar to React or Redux, the normal approach is to copy each level of thestate object. This is done with the spread operator `...`, and by manuallymerging that in with the new state values. Like so:
```ts 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! Let's explore some alternatives that will make your lifeeasier.
### With Immer
Many people use [Immer](https://github.com/immerjs/immer) to update nestedvalues. Immer can be used anytime you need to update nested state such as inReact, Redux and of course, Zustand!
You can use Immer to shorten your state updates for deeply nested object. Let'stake a look at an example:
```ts immerInc: () => set(produce((state: State) => { ++state.deep.nested.obj.count })),```
What a reduction! Please take note of the [gotchas listed here](../../reference/integrations/immer-middleware.md).
### With optics-ts
There is another option with [optics-ts](https://github.com/akheron/optics-ts/):
```ts opticsInc: () => set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),```
Unlike Immer, optics-ts doesn't use proxies or mutation syntax.
### With Ramda
You can also use [Ramda](https://ramdajs.com/):
```ts ramdaInc: () => set(R.modifyPath(["deep", "nested", "obj", "count"], (c) => c + 1)),```
Both ramda and optics-ts also work with types.
### Demo
https://stackblitz.com/edit/vitejs-vite-j6bjdygu