useMap
The useMap hook manages a Map as React state. Every change produces a new Map instance, so it works correctly in dependency arrays and with React.memo.
Usage
Installation
import { useMap } from "hookstorm";
Parameters
- initialEntries — (optional) Initial key/value pairs, for example
[["a", 1]]or an existingMap.
Return Values
- map — The current
Map. Treat it as read-only and update it through the actions below. - set(key, value) — Adds or updates a key.
- setAll(entries) — Replaces the whole map with the given entries.
- remove(key) — Deletes a key.
- clear() — Removes all entries.
- reset() — Restores the initial entries.
Example Usage
import { ReactElement } from "react";
import { useMap } from "hookstorm";
export default function Cart(): ReactElement {
const { map: cart, set, remove, clear } = useMap<string, number>([["apple", 1]]);
return (
<div>
{Array.from(cart.entries()).map(([item, qty]) => (
<p key={item}>
{item}: {qty}
<button onClick={() => set(item, qty + 1)}>+</button>
<button onClick={() => remove(item)}>Remove</button>
</p>
))}
<button onClick={() => set("banana", 1)}>Add banana</button>
<button onClick={clear}>Clear</button>
</div>
);
}
Notes
- Action functions have a stable identity, so they are safe to pass to memoized children.
- Removing a key that does not exist does not cause a re-render.
resetuses the entries from the first render; later changes toinitialEntriesare ignored.