Use these patterns to assign new values, calculate updates from current state, copy nested data, and return a store to its initial state. The example renders an age counter, a horizontal-position slider, a name form with a nested counter, and a movable dot stored as an array.
Start from the project in the React quick start. Keep its entry file, React wrapper, and stylesheet imports; the files below add components and change what App renders. No additional package is needed.
Prepare stores that can reset together
Wrap create to register resets for the stores below; see How Zustand works for the hook and its store API.
- Add this helper. It accepts the library's
StateCreatortype and creates the same bound hook ascreate. - Register a reset function for each store. Calling
resetAllStores()restores every registered store with its complete initial state.
tsimport { create } from 'zustand'
import type { StateCreator } from 'zustand'
const storeResetFns = new Set<() => void>()
export function createResettable<T>(stateCreator: StateCreator<T>) {
const store = create<T>()(stateCreator)
storeResetFns.add(() => {
store.setState(store.getInitialState(), true)
})
return store
}
export function resetAllStores() {
storeResetFns.forEach((reset) => reset())
}
This helper suits module-level stores that live for the lifetime of this application. It follows the authors' reset-function registry pattern; the final step connects it to a button.
Updating state based on previous state
Pass an updater function to set when the next value depends on the current value. Zustand calls it with the current store state, so successive calls each see the preceding update.
- Define an action that accepts either a number or a function from the current number to the next number.
- Resolve that argument inside
set, not from a value captured during rendering. - Render the selected age and actions. Clicking +3 performs three increments and changes the initial age from 42 to 45.
tsximport { createResettable } from './resettable'
type AgeStore = {
age: number
setAge: (nextAge: number | ((currentAge: number) => number)) => void
}
const useAgeStore = createResettable<AgeStore>((set) => ({
age: 42,
setAge: (nextAge) => {
set((state) => ({
age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,
}))
},
}))
export function AgeCounter() {
const age = useAgeStore((state) => state.age)
const setAge = useAgeStore((state) => state.setAge)
function increment() {
setAge((currentAge) => currentAge + 1)
}
return (
<section>
<h2>Age: {age}</h2>
<button onClick={increment}>+1</button>
<button onClick={() => {
increment()
increment()
increment()
}}>+3</button>
<button onClick={() => setAge(42)}>Set age to 42</button>
</section>
)
}
The action's support for function arguments comes from its implementation: Zustand does not automatically give every custom action updater semantics. The repository's React counter demo uses the same set((state) => …) pattern for an increment action.
Updating primitives in state
Strings, numbers, and booleans are updated by assigning new values. They can be fields of an object, as age is above, or the entire store state.
- Create a store whose state is a number.
- Call
setState(nextX, true)to replace that state. - Bind the number to a range input and a visible dot. Moving the slider changes both the displayed coordinate and the dot's horizontal position.
tsximport { createResettable } from './resettable'
const useXStore = createResettable<number>(() => 0)
export function PrimitivePosition() {
const x = useXStore()
const setX = (nextX: number) => useXStore.setState(nextX, true)
return (
<section>
<h2>Primitive position</h2>
<label>
X: {x}
<input
type="range"
min={0}
max={280}
value={x}
onChange={(event) => setX(event.currentTarget.valueAsNumber)}
/>
</label>
<div style={{ position: 'relative', width: 300, height: 40,
background: '#eee' }}>
<div style={{ position: 'absolute', left: x, top: 10,
width: 20, height: 20, borderRadius: '50%', background: 'red' }} />
</div>
</section>
)
}
The true argument explicitly selects replacement, as in the authors' primitive-position example. Non-object values also replace state when the argument is omitted.
Updating objects in state
For flat updates, pass the fields that change to set; its shallow merge preserves other top-level fields and actions. For nested updates, copy every object on the path to the changed field.
- Add a name action that updates only
firstName. - Add a nested-counter action that copies
deep,nested, andobjbefore changingcount. - Select the fields and actions in the form. Typing a name updates the greeting without changing the last name. Clicking Increment nested count changes the count while preserving its label.
tsximport { createResettable } from './resettable'
type PersonStore = {
firstName: string
lastName: string
deep: {
nested: {
obj: { count: number; label: string }
}
}
updateFirstName: (firstName: string) => void
normalInc: () => void
reset: () => void
}
const usePersonStore = createResettable<PersonStore>((set, _get, store) => ({
firstName: 'Ada',
lastName: 'Lovelace',
deep: { nested: { obj: { count: 0, label: 'Visits' } } },
updateFirstName: (firstName) => set({ firstName }),
normalInc: () => set((state) => ({
deep: {
...state.deep,
nested: {
...state.deep.nested,
obj: {
...state.deep.nested.obj,
count: state.deep.nested.obj.count + 1,
},
},
},
})),
reset: () => set(store.getInitialState()),
}))
export function PersonForm() {
const firstName = usePersonStore((state) => state.firstName)
const lastName = usePersonStore((state) => state.lastName)
const counter = usePersonStore((state) => state.deep.nested.obj)
const updateFirstName = usePersonStore((state) => state.updateFirstName)
const normalInc = usePersonStore((state) => state.normalInc)
const reset = usePersonStore((state) => state.reset)
return (
<section>
<h2>Object updates</h2>
<label>
First name
<input value={firstName}
onChange={(event) => updateFirstName(event.currentTarget.value)} />
</label>
<p>Hello, {firstName} {lastName}!</p>
<p>{counter.label}: {counter.count}</p>
<button onClick={normalInc}>Increment nested count</button>
<button onClick={reset}>Reset person</button>
</section>
)
}
The reset action uses the third initializer argument to read store.getInitialState() when clicked. The initial object includes both data and actions. The callback does not read the store during initialization.
For the rules behind these copies, see Immutable state and merging. For mutation-style nested updates with Immer, continue with Update state with Immer. The authors also demonstrate optics-ts and Ramda as alternatives to manual copying in their nested-update demo.
Updating arrays in state
Create a new array for an array update. When the array is the entire store state, use replacement rather than merging its indexed properties into an object.
- Define the position as a typed two-number tuple.
- Replace it with a new tuple on pointer movement. Calculate coordinates relative to the drawing area rather than the viewport.
- Use an updater for Move right 10 so the move starts from the current position. The red dot follows the pointer inside the gray area, and the button moves it horizontally.
tsximport { createResettable } from './resettable'
type PositionStore = [number, number]
const usePositionStore = createResettable<PositionStore>(() => [20, 20])
export function ArrayPosition() {
const [x, y] = usePositionStore()
const setPosition = (nextPosition: PositionStore) => {
usePositionStore.setState(nextPosition, true)
}
return (
<section>
<h2>Array position: {x}, {y}</h2>
<button onClick={() => {
usePositionStore.setState(([currentX, currentY]) =>
[Math.min(currentX + 10, 290), currentY], true)
}}>Move right 10</button>
<div
onPointerMove={(event) => {
const bounds = event.currentTarget.getBoundingClientRect()
setPosition([
Math.max(10, Math.min(290, event.clientX - bounds.left)),
Math.max(10, Math.min(190, event.clientY - bounds.top)),
])
}}
style={{ position: 'relative', width: 300, height: 200,
background: '#eee' }}
>
<div style={{ position: 'absolute', left: x - 10, top: y - 10,
width: 20, height: 20, borderRadius: '50%', background: 'red',
pointerEvents: 'none' }} />
</div>
</section>
)
}
For an array field inside an object store, return an object containing the new array instead: the default shallow merge then preserves the other top-level fields. Use immutable operations such as spread, concat, filter, slice, or map to create that new array.
Reset a store to its initial state
getInitialState() returns the state produced by the initializer, not the state at the most recent render. The person form's Reset person button restores its name and nested counter through set(store.getInitialState()).
- Change
src/App.tsxto render the four components. Leave the quick start's entry file unchanged so it still mountsApp. - Connect Reset all stores to the registry helper. Edit several sections, then click it: the age returns to 42, the slider to 0, the name to Ada Lovelace, the nested count to 0, and the array position to
[20, 20].
tsximport { AgeCounter } from './AgeCounter'
import { PrimitivePosition } from './PrimitivePosition'
import { PersonForm } from './PersonForm'
import { ArrayPosition } from './ArrayPosition'
import { resetAllStores } from './resettable'
export default function App() {
return (
<main>
<h1>Update and reset state</h1>
<AgeCounter />
<PrimitivePosition />
<PersonForm />
<ArrayPosition />
<button onClick={resetAllStores}>Reset all stores</button>
</main>
)
}
Compare the authors' runnable single-store reset demo and multiple-store reset demo. The registry uses setState(store.getInitialState(), true) so the reset supplies the complete state, including actions.
Choose merge or replacement
set is the initializer's state-update function; setState is the corresponding method on the returned hook. Both accept a value or an updater function and an optional second argument.
| Option | Type | Default | What it does |
|---|---|---|---|
replace | boolean | Omitted: merge non-null objects; replace other values | Chooses whether the update merges with or replaces current state. |
| Choice | Effect |
|---|---|
| Omitted | Shallowly merges non-null object updates; replaces primitives and null. Arrays count as objects, so use true for an array-root store. |
false | Forces a shallow merge. Use object updates for this mode. |
true | Replaces the entire state. Supply the complete state, as with the initial-state reset. |
Updates through set and setState return void. To inspect state outside React, call the hook's getState(); inside a component, use the hook with a selector so the displayed value follows store updates.
Pitfalls and related guides
- Keep object and array references immutable, including the initial objects used for reset. See Immutable state and merging.
- When replacing an object store, use the full state shape, including actions. See Type stores and selectors for replacement typing.
- For deciding which fields a component subscribes to, see Selectors and rendering.
- For updates to collection types, see Update Maps and Sets.
Was this page helpful?