# Update Maps and Sets

Use a `Map` for keyed values and a `Set` for unique values. This example displays user names and selected user IDs, with controls to add, update, remove, toggle, and clear entries. Each action creates a new collection instance before passing it to Zustand's `set`.

Start from the project in the [React quick start](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/react-quick-start), with `zustand` installed. Add the files below without changing the starter's entry file, stylesheet imports, or `StrictMode` wrapper.

## Set

1. Define the collection types explicitly: `Map<string, string>` stores names by user ID, and `Set<string>` stores selected IDs.
2. Use [`create`](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/zustand#create) to bind the store to a React hook. Keep the collection updates in store actions.

The initial state contains Ada and the selected ID `ada`. The Map and Set are independent: removing a name does not remove its ID from the selection.

```ts title="src/collection-store.ts"
import { create } from 'zustand'

type CollectionStore = {
  users: Map<string, string>
  selectedIds: Set<string>
  saveUser: (id: string, name: string) => void
  removeUser: (id: string) => void
  saveTwoUsers: () => void
  clearUsers: () => void
  selectId: (id: string) => void
  deselectId: (id: string) => void
  toggleId: (id: string) => void
  clearSelection: () => void
}

export const useCollectionStore = create<CollectionStore>()((set) => ({
  users: new Map<string, string>([['ada', 'Ada']]),
  selectedIds: new Set<string>(['ada']),

  saveUser: (id, name) =>
    set((state) => ({ users: new Map(state.users).set(id, name) })),

  removeUser: (id) =>
    set((state) => {
      const next = new Map(state.users)
      next.delete(id)
      return { users: next }
    }),

  saveTwoUsers: () =>
    set((state) => {
      const next = new Map(state.users)
      next.set('ada', 'Ada Lovelace')
      next.set('grace', 'Grace Hopper')
      return { users: next }
    }),

  clearUsers: () => set({ users: new Map<string, string>() }),

  selectId: (id) =>
    set((state) => ({ selectedIds: new Set(state.selectedIds).add(id) })),

  deselectId: (id) =>
    set((state) => {
      const next = new Set(state.selectedIds)
      next.delete(id)
      return { selectedIds: next }
    }),

  toggleId: (id) =>
    set((state) => {
      const next = new Set(state.selectedIds)
      next.has(id) ? next.delete(id) : next.add(id)
      return { selectedIds: next }
    }),

  clearSelection: () => set({ selectedIds: new Set<string>() }),
}))
```

`set` shallowly merges each partial update, preserving the other collection and the actions. The callback form receives the current state, so each copy starts from the collection at the time the action runs.

## Reading a Map

1. Select the Map itself with the store hook.
2. Read individual values with `get()` and convert its entries to an array inside the component's render.

This component initially shows `Ada: Ada` and one list entry, `ada: Ada`. Updating the Map through the actions updates the displayed name and list.

```tsx title="src/MapReader.tsx"
import { useCollectionStore } from './collection-store'

export function MapReader() {
  const users = useCollectionStore((state) => state.users)

  return (
    <section>
      <h2>Users ({users.size})</h2>
      <p>Ada: {users.get('ada') ?? 'Not in the Map'}</p>
      <ul>
        {Array.from(users, ([id, name]) => (
          <li key={id}>{id}: {name}</li>
        ))}
      </ul>
    </section>
  )
}
```

## Reading a Set

1. Select the Set itself with the store hook.
2. Use `has()` to check membership and iterate over the Set to display its values.

This component initially shows `Ada selected: yes` and the ID `ada`. Its count and membership text follow changes from any of the selection actions.

```tsx title="src/SetReader.tsx"
import { useCollectionStore } from './collection-store'

export function SetReader() {
  const selectedIds = useCollectionStore((state) => state.selectedIds)

  return (
    <section>
      <h2>Selected IDs ({selectedIds.size})</h2>
      <p>Ada selected: {selectedIds.has('ada') ? 'yes' : 'no'}</p>
      <ul>
        {Array.from(selectedIds, (id) => <li key={id}>{id}</li>)}
      </ul>
    </section>
  )
}
```

Both readers select an existing collection reference. They create display arrays after selection, not inside the selector. For computed selector outputs, see [Select computed state](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/select-computed-state).

## Updating a Map

1. Add these controls alongside `MapReader`.
2. Click **Save Ada Lovelace** to insert or update `ada`, **Save two users** to update two entries in one `set` call, or **Remove Ada** to delete one entry.
3. Click **Clear users** to replace the Map with an empty, explicitly typed Map.

The actions in `collection-store.ts` copy the current Map before calling `set()` or `delete()` on the copy. The reader displays the resulting entries; clearing shows a count of zero and `Not in the Map`.

```tsx title="src/MapControls.tsx"
import { useCollectionStore } from './collection-store'

export function MapControls() {
  const saveUser = useCollectionStore((state) => state.saveUser)
  const removeUser = useCollectionStore((state) => state.removeUser)
  const saveTwoUsers = useCollectionStore((state) => state.saveTwoUsers)
  const clearUsers = useCollectionStore((state) => state.clearUsers)

  return (
    <div>
      <button onClick={() => saveUser('ada', 'Ada Lovelace')}>
        Save Ada Lovelace
      </button>
      <button onClick={saveTwoUsers}>Save two users</button>
      <button onClick={() => removeUser('ada')}>Remove Ada</button>
      <button onClick={clearUsers}>Clear users</button>
    </div>
  )
}
```

## Updating a Set

1. Add these controls alongside `SetReader`.
2. Click **Select Grace** to add `grace`, **Deselect Ada** to remove `ada`, or **Toggle Ada** to invert Ada's membership.
3. Click **Clear selection** to replace the Set with an empty, explicitly typed Set.

Adding an existing ID keeps one occurrence. Toggling deletes the ID when present and adds it when absent. The count and list reflect the resulting Set, including an empty list after clearing.

```tsx title="src/SetControls.tsx"
import { useCollectionStore } from './collection-store'

export function SetControls() {
  const selectId = useCollectionStore((state) => state.selectId)
  const deselectId = useCollectionStore((state) => state.deselectId)
  const toggleId = useCollectionStore((state) => state.toggleId)
  const clearSelection = useCollectionStore((state) => state.clearSelection)

  return (
    <div>
      <button onClick={() => selectId('grace')}>Select Grace</button>
      <button onClick={() => deselectId('ada')}>Deselect Ada</button>
      <button onClick={() => toggleId('ada')}>Toggle Ada</button>
      <button onClick={clearSelection}>Clear selection</button>
    </div>
  )
}
```

### Render the readers and controls

Add this component, then import `CollectionsDemo` from `./CollectionsDemo` in your existing `src/App.tsx` and add `<CollectionsDemo />` inside its returned JSX. Keep the starter's existing imports and content. Its entry file continues to mount `App`.

```tsx title="src/CollectionsDemo.tsx"
import { MapReader } from './MapReader'
import { MapControls } from './MapControls'
import { SetReader } from './SetReader'
import { SetControls } from './SetControls'

export default function CollectionsDemo() {
  return (
    <section style={{ minHeight: 400 }}>
      <h1>Map and Set entries</h1>
      <MapReader />
      <MapControls />
      <SetReader />
      <SetControls />
    </section>
  )
}
```

Run the project's development server with `npm run dev`. On first load, you see one user, one selected ID, and controls for both collections. The two panels share the same mounted store binding.

## Collection types and update boundaries

There are no collection-specific Zustand options to configure. Choose the collection by the operations you need:

| Collection | Example type | Reads | Updates |
| --- | --- | --- | --- |
| `Map` | `Map<string, string>` | `get(key)`, `has(key)`, `size`, iteration | Copy, then `set(key, value)` or `delete(key)`; clear with a new empty Map |
| `Set` | `Set<string>` | `has(value)`, `size`, iteration | Copy, then `add(value)` or `delete(value)`; toggle with `has(value)`; clear with a new empty Set |

Provide explicit element types for empty collections, as in `new Map<string, string>()` and `new Set<string>()`. These constructors preserve the intended key, value, and element types without depending on inference from an empty array.

Keep mutations on the new copy, not on the collection selected from the store. For the reference and nested-object rules behind this pattern, see [Immutable state and merging](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/immutable-state-and-merging).

## Live demo

Explore the authors' [Map and Set demo](https://stackblitz.com/edit/vitejs-vite-5cu5ddvx) to compare collection updates in a running application.

## Related

- [Organize store actions](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/organize-store-actions) — Keep data and the actions that update it together.
- [Selectors and rendering](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/selectors-and-rendering) — Choose the values each component subscribes to.
- [Type stores and selectors](https://bench-zustand-61.atloria.app/p/bench-zustand-61-pSJCWrWW5Y/developer/type-stores-and-selectors) — Carry state and action types through your store hooks.
