UseMap
guarahooks/use-mapFreeHook
Manages a Map of key/value pairs with ease.
Live preview
live · rendered by the registry
Rendered by guarahooks on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://guarahooks.com/r/use-map.jsonSource
1'use client';23import { useCallback, useMemo, useState } from 'react';45export type UseMapResult<K, V> = {6 map: Map<K, V>;7 set: (key: K, value: V) => void;8 delete: (key: K) => void;9 has: (key: K) => boolean;10 clear: () => void;11 reset: () => void;12 setValue: (newMap: Map<K, V>) => void;13 get: (key: K) => V | undefined;14 getAll: () => [K, V][];15};1617export function useMap<K, V>(18 initialMap: Iterable<[K, V]> = [],19): UseMapResult<K, V> {20 const [map, setMap] = useState<Map<K, V>>(() => new Map(initialMap));21 const initial = useMemo(() => new Map(initialMap), [initialMap]);2223 const setEntry = useCallback((key: K, value: V) => {24 setMap((prev) => {25 const current = prev.get(key);26 if (prev.has(key) && current === value) return prev;27 const next = new Map(prev);28 next.set(key, value);29 return next;30 });31 }, []);3233 const deleteEntry = useCallback((key: K) => {34 setMap((prev) => {35 if (!prev.has(key)) return prev;36 const next = new Map(prev);37 next.delete(key);38 return next;39 });40 }, []);4142 const hasKey = useCallback((key: K) => map.has(key), [map]);4344 const clear = useCallback(() => {45 setMap(new Map());46 }, []);4748 const reset = useCallback(() => {49 setMap(new Map(initial));50 }, [initial]);5152 const setValue = useCallback((newMap: Map<K, V>) => {53 setMap(new Map(newMap));54 }, []);5556 const get = useCallback((key: K) => map.get(key), [map]);5758 const getAll = useCallback(() => Array.from(map.entries()), [map]);5960 return {61 map,62 set: setEntry,63 delete: deleteEntry,64 has: hasKey,65 clear,66 reset,67 setValue,68 get,69 getAll,70 };71}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
