Skip to content
Myr

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 file

Take it

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

lines 1–25why, one step back
1---
2title: Updating state3nav: 44---56## Flat updates78Updating state with Zustand is simple! Call the provided `set` function with9the new state, and it will be shallowly merged with the existing state in the10store. **Note** See next section for nested state.1112```tsx13import { create } from 'zustand'1415type State = {16 firstName: string17 lastName: string18}1920type Action = {21 updateFirstName: (firstName: State['firstName']) => void22 updateLastName: (lastName: State['lastName']) => void23}2425// Create your store, which includes both state and (optionally) actions

docs(updating-state): use curried create form with explicit state type (#3503)Seydi Charyyevbefore adoption038b938

line 26why, one step back
26const usePersonStore = create<State & Action>()((set) => ({

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

lines 27–141why, one step back
27 firstName: '',
28 lastName: '',29 updateFirstName: (firstName) => set(() => ({ firstName: firstName })),30 updateLastName: (lastName) => set(() => ({ lastName: lastName })),31}))3233// In consuming app34function App() {35 // "select" the needed state and actions, in this case, the firstName value36 // and the action updateFirstName37 const firstName = usePersonStore((state) => state.firstName)38 const updateFirstName = usePersonStore((state) => state.updateFirstName)3940 return (41 <main>42 <label>43 First name44 <input45 // Update the "firstName" state46 onChange={(e) => updateFirstName(e.currentTarget.value)}47 value={firstName}48 />49 </label>5051 <p>52 Hello, <strong>{firstName}!</strong>53 </p>54 </main>55 )56}57```5859## Deeply nested object6061If you have a deep state object like this:6263```ts64type State = {65 deep: {66 nested: {67 obj: { count: number }68 }69 }70}71```7273Updating nested state requires some effort to ensure the process is completed74immutably.7576### Normal approach7778Similar to React or Redux, the normal approach is to copy each level of the79state object. This is done with the spread operator `...`, and by manually80merging that in with the new state values. Like so:8182```ts83 normalInc: () =>84 set((state) => ({85 deep: {86 ...state.deep,87 nested: {88 ...state.deep.nested,89 obj: {90 ...state.deep.nested.obj,91 count: state.deep.nested.obj.count + 192 }93 }94 }95 })),96```9798This is very long! Let's explore some alternatives that will make your life99easier.100101### With Immer102103Many people use [Immer](https://github.com/immerjs/immer) to update nested104values. Immer can be used anytime you need to update nested state such as in105React, Redux and of course, Zustand!106107You can use Immer to shorten your state updates for deeply nested object. Let's108take a look at an example:109110```ts111 immerInc: () =>112 set(produce((state: State) => { ++state.deep.nested.obj.count })),113```114115What a reduction! Please take note of the [gotchas listed here](../../reference/integrations/immer-middleware.md).116117### With optics-ts118119There is another option with [optics-ts](https://github.com/akheron/optics-ts/):120121```ts122 opticsInc: () =>123 set(O.modify(O.optic<State>().path("deep.nested.obj.count"))((c) => c + 1)),124```125126Unlike Immer, optics-ts doesn't use proxies or mutation syntax.127128### With Ramda129130You can also use [Ramda](https://ramdajs.com/):131132```ts133 ramdaInc: () =>134 set(R.modifyPath(["deep", "nested", "obj", "count"], (c) => c + 1)),135```136137Both ramda and optics-ts also work with types.138139### Demo140141https://stackblitz.com/edit/vitejs-vite-j6bjdygu