useMap
Map state with set, remove, and reset helpers.
Map state with set, remove, and reset helpers.
Import
import { useMap } from '@kamod-ch/hooks'Live demo
Basic demo
Map state with set, remove, and reset helpers.
{
"status": "ready"
}import { useMap } from '@kamod-ch/hooks'
export default function UseMapDemo() {
const [map, actions] = useMap([['status', 'ready']])
return (
<div>
<pre>{JSON.stringify(Object.fromEntries(map), null, 2)}</pre>
<div class="demo-actions">
<button type="button" onClick={() => actions.set('status', 'loading')}>Set loading</button>
<button type="button" onClick={() => actions.set('theme', 'dark')}>Add theme</button>
<button type="button" onClick={() => actions.remove('status')}>Remove status</button>
<button type="button" onClick={actions.reset}>Reset</button>
</div>
</div>
)
}
API
TypeScript signature
declare function useMap<K, T>(initialValue?: Iterable<readonly [K, T]>): readonly [Map<K, T>, {
readonly set: (this: unknown, key: K, entry: T) => void;
readonly setAll: (this: unknown, newMap: Iterable<readonly [K, T]>) => void;
readonly remove: (this: unknown, key: K) => void;
readonly reset: (this: unknown) => void;
readonly get: (this: unknown, key: K) => T;
}];
export default useMap;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.