useMapstate
useMap
NewSSR SAFEA reactive Map instance synchronized with React state that triggers re-renders on mutation.
$ pnpm dlx shadcn@latest add @byphongphan/use-mapRequires
@byphongphan in components.jsonuse-map.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-mapRequires
@byphongphan in components.jsonUsage
Managing Dynamic Configuration
Complex Object Keys or Caching
Features
- Full Native Compatibility: Retains all native
Mapprototype methods (get,has,size,keys,values,entries, andfor..ofiterators). - Reactive Mutations: Invoking
.set(),.delete(), or.clear()triggers React state updates automatically. - Convenience Utilities: Adds
.reset()to return to initial entries and.setAll(entries)for atomic bulk replacements. - Lazy Initial State: Supports factory functions
() => entriesfor expensive initial calculations. - Type-Safe Generics: Preserves strong typing across both key (
K) and value (V) types.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialEntries | Iterable<readonly [K, V]> | (() => Iterable<readonly [K, V]>) | — | Optional initial key-value pairs or a lazy initializer function. |
Returns
Returns an extended ReactiveMap<K, V> instance:
| Property / Method | Type | Description |
|---|---|---|
size | number | Current number of entries in the map. |
get(key) | (key: K) => V | undefined | Retrieves the value associated with key. |
has(key) | (key: K) => boolean | Returns true if an entry with key exists. |
set(key, value) | (key: K, value: V) => this | Inserts or updates an entry and triggers a React re-render. |
delete(key) | (key: K) => boolean | Removes the specified entry and triggers a React re-render. |
clear() | () => void | Removes all entries and triggers a React re-render. |
reset() | () => void | Restores the map back to its original initial entries. |
setAll(entries) | (entries: Iterable<readonly [K, V]>) => void | Replaces all entries with a new set of entries in one tick. |
entries() | () => IterableIterator<[K, V]> | Returns an iterator over [key, value] pairs. |
keys() | () => IterableIterator<K> | Returns an iterator over all keys. |
values() | () => IterableIterator<V> | Returns an iterator over all values. |