@supunlakmal/hooks
Version:
A collection of reusable React hooks
59 lines • 2.36 kB
JavaScript
import { useMemo, useState } from 'react';
/**
* Custom hook to manage state as a Map, providing helper functions.
*
* @template K - The type of the keys in the Map.
* @template V - The type of the values in the Map.
* @param initialMap - Optional initial Map or an iterable of key-value pairs.
* @returns A tuple containing the current Map state and an actions object.
*/
export const useMap = (initialMap) => {
const [map, setMap] = useState(() => new Map(initialMap));
const actions = useMemo(() => ({
set: (key, value) => {
setMap((prevMap) => {
// Create a new map to ensure immutability and trigger re-render
const newMap = new Map(prevMap);
newMap.set(key, value);
return newMap;
});
},
setAll: (entries) => {
setMap((prevMap) => {
// Allow setting multiple entries, potentially merging or replacing
const newMap = new Map(prevMap); // Start with previous entries
// Use Array.from to convert Iterable to Array to avoid the downlevelIteration issue
Array.from(entries).forEach(([key, value]) => {
newMap.set(key, value);
});
return newMap;
});
},
remove: (key) => {
setMap((prevMap) => {
if (!prevMap.has(key)) {
return prevMap; // No change if key doesn't exist
}
const newMap = new Map(prevMap);
newMap.delete(key);
return newMap;
});
},
reset: () => {
// Reset back to the initial state provided when the hook was first called
setMap(new Map(initialMap));
},
clear: () => {
// Clear the map completely
setMap(new Map());
},
get: (key) => {
// Directly access the current map state. Since map is state,
// this will reflect the latest version on re-render.
// Note: This doesn't cause a re-render if only `get` is used.
return map.get(key);
},
}), [initialMap]); // Recalculate actions only if initialMap reference changes
return [map, actions];
};
//# sourceMappingURL=useMap.js.map