Map-backed state
Maintain keyed records while preserving immutable updates.
Zustand · Const
Use Map and Set values in Zustand by replacing them with newly created instances on every update. This preserves reference changes so Zustand can detect updates and re-render subscribers.
The page explains how to store Map and Set values in Zustand while preserving immutable update semantics. Clone the collection, apply the mutation to the clone, and return the new reference so Zustand can detect the change.
set((state) => ({ collection: new Map(state.collection) }))import { create } from 'zustand'
type Store = {
selected: Set<string>
toggle: (id: string) => void
}
const useStore = create<Store>((set) => ({
selected: new Set<string>(),
toggle: (id) =>
set((state) => {
const next = new Set(state.selected)
next.has(id) ? next.delete(id) : next.add(id)
return { selected: next }
}),
}))
useStore.getState().toggle('a')
console.log(useStore.getState().selected.has('a'))Creates a Zustand store with a Set and toggles membership by cloning the Set before changing it.
Maintain keyed records while preserving immutable updates.
Track selected, enabled, or expanded identifiers.
Toggle membership in a collection from an action.
Use a copy of the existing collection, mutate that copy, and return it from set. For example, create a new Map from the old Map before calling set, delete, or clear operations.
Follow-up: Why is returning the original Map unsafe? Because its reference is unchanged, so Zustand may not detect a state change and subscribers may not re-render.
Create a new Set from the current Set, then add, delete, or toggle the item on the copy. Return the new Set in the state update.
Follow-up: How would you toggle membership? Check whether the copied Set has the item; delete it when present, otherwise add it.
Zustand detects changes by comparing references. Since Map and Set are mutable, in-place operations preserve the reference and do not provide the new reference needed for reliable change detection.
Follow-up: What should an empty typed collection look like in TypeScript? Use an explicit assertion such as new Set([] as string[]) or new Map([] as [string, User][]).
setuseSomeStoreMapSet