useMap
State & dataA React hook for managing Map state with immutable updates
Install
$ npm install @usefy/use-mapQuick start
useMap.tsx
import { useMap } from "@usefy/use-map";
function Settings() {
const [prefs, { set, remove, reset }] = useMap<string, boolean>([
["darkMode", false],
["beta", true],
]);
return (
<label>
<input
type="checkbox"
checked={prefs.get("darkMode") ?? false}
onChange={(e) => set("darkMode", e.target.checked)}
/>
Dark mode
</label>
);
}API reference
useMap<K, V>(initialState?)
Returns a tuple of the current read-only map and a stable actions object.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialState | MapInitializer<K, V> | empty | A Map, an iterable of [key, value] tuples, or a factory returning one (evaluated once) |
Returns [map, actions]
| Item | Type | Description |
|---|---|---|
map | ReadonlyMap<K, V> | Current map. Read via get/has/size/iteration |
actions | UseMapActions<K, V> | Stable action handlers (see below) |
Actions
| Action | Signature | Description |
|---|---|---|
set | (key: K, value: V) => void | Set/overwrite a key. Setting a key to its current value is a no-op |
setAll | (entries: Iterable<[K, V]>) => void | Replace the entire map with the given entries |
remove | (key: K) => void | Remove a key. Removing an absent key is a no-op |
reset | () => void | Restore the initial entries (a fresh copy) |
clear | () => void | Remove all entries. Clearing an empty map is a no-op |
get | (key: K) => V | undefined | Read a key's value (stable, always reflects latest state) |
The returned
mapis aReadonlyMap, so callingmap.set(...)directly is a TypeScript error. Use the actions — mutating the map in place would bypass React state and break re-renders.
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.