Skip to content
Myr

maps-and-sets-usage.md

This file

Path

docs/learn/guides/maps-and-sets-usage.md

115 lines · 1.9 KiB · Markdown

Last changed by

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

History of this file

Take it

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

lines 1–115why, one step back
1---
2title: Map and Set Usage3nav: 84---56# Map and Set in Zustand78Map and Set are mutable data structures. To use them in Zustand, you must create new instances when updating.910## Map1112### Reading a Map1314```typescript15const foo = useSomeStore((state) => state.foo)16```1718### Updating a Map1920Always create a new Map instance:2122```ts23// Update single entry24set((state) => ({25 foo: new Map(state.foo).set(key, value),26}))2728// Delete entry29set((state) => {30 const next = new Map(state.foo)31 next.delete(key)32 return { foo: next }33})3435// Update multiple entries36set((state) => {37 const next = new Map(state.foo)38 next.set('key1', 'value1')39 next.set('key2', 'value2')40 return { foo: next }41})4243// Clear44set({ foo: new Map() })45```4647## Set4849### Reading a Set5051```ts52const bar = useSomeStore((state) => state.bar)53```5455### Updating a Set5657Always create a new Set instance:5859```ts60// Add item61set((state) => ({62 bar: new Set(state.bar).add(item),63}))6465// Delete item66set((state) => {67 const next = new Set(state.bar)68 next.delete(item)69 return { bar: next }70})7172// Toggle item73set((state) => {74 const next = new Set(state.bar)75 next.has(item) ? next.delete(item) : next.add(item)76 return { bar: next }77})7879// Clear80set({ bar: new Set() })81```8283## Why New Instances?8485Zustand detects changes by comparing references. Mutating a Map or Set doesn't change its reference:8687```ts88// ❌ Wrong - same reference, no re-render89set((state) => {90 state.foo.set(key, value)91 return { foo: state.foo }92})9394// ✅ Correct - new reference, triggers re-render95set((state) => ({96 foo: new Map(state.foo).set(key, value),97}))98```99100## Pitfall: Type Hints for Empty Collections101102Provide type hints when initializing empty Maps and Sets:103104```ts105{106 ids: new Set([] as string[]),107 users: new Map([] as [string, User][])108}109```110111Without type hints, TypeScript infers `never[]` which prevents adding items later.112113## Demos114115Basic: https://stackblitz.com/edit/vitejs-vite-5cu5ddvx