react-use/src/useMap.ts
Renovate Bot a27f09fd36
chore: refactoring and rearrangement.
More DRY code. Also move non-hooks to separate directories.

BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint`
BREAKING CHANGE: `comps` directory renamed to `component`
2021-01-30 23:30:26 +03:00

48 lines
1.1 KiB
TypeScript

import { useCallback, useMemo, useState } from 'react';
export interface StableActions<T extends object> {
set: <K extends keyof T>(key: K, value: T[K]) => void;
setAll: (newMap: T) => void;
remove: <K extends keyof T>(key: K) => void;
reset: () => void;
}
export interface Actions<T extends object> extends StableActions<T> {
get: <K extends keyof T>(key: K) => T[K];
}
const useMap = <T extends object = any>(initialMap: T = {} as T): [T, Actions<T>] => {
const [map, set] = useState<T>(initialMap);
const stableActions = useMemo<StableActions<T>>(
() => ({
set: (key, entry) => {
set((prevMap) => ({
...prevMap,
[key]: entry,
}));
},
setAll: (newMap: T) => {
set(newMap);
},
remove: (key) => {
set((prevMap) => {
const { [key]: omit, ...rest } = prevMap;
return rest as T;
});
},
reset: () => set(initialMap),
}),
[set]
);
const utils = {
get: useCallback((key) => map[key], [map]),
...stableActions,
} as Actions<T>;
return [map, utils];
};
export default useMap;