Skip to content

Commit

Permalink
chore(useMap): replace state with ref to persist obj reference
Browse files Browse the repository at this point in the history
  • Loading branch information
steventhan committed Apr 5, 2023
1 parent 9c42c99 commit ed1a42f
Showing 1 changed file with 22 additions and 15 deletions.
37 changes: 22 additions & 15 deletions src/hooks/useMap.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,43 @@
import { useCallback, useState } from 'react';
import { useCallback, useRef } from 'react';
import { useUpdate } from 'react-use';

export default function useMap<T>(defaultValue: T[], keyMapper: (value: T) => any = (x) => x) {
const [map, setMap] = useState(new Map(defaultValue.map((val: T) => [keyMapper(val), val])));
const mapRef = useRef(new Map(defaultValue.map((val: T) => [keyMapper(val), val])));
const update = useUpdate();
const { current: map } = mapRef;

const has = (value: T) => map.has(keyMapper(value));

const add = (value: T) => {
map.set(keyMapper(value), value);

const newMap = new Map(map);
setMap(newMap);

return newMap;
update();
return map;
};

const remove = (value: T) => {
map.delete(keyMapper(value));

const newMap = new Map(map);
setMap(newMap);

return newMap;
update();
return map;
};

const toggle = (value: T) => {
if (has(value)) {
return remove(value);
}
return add(value);
};
const clear = () => map.clear();

const clear = () => {
map.clear();
update();
};

const replace = useCallback(
(values: T[]) => {
setMap(new Map(values ? values.map((val: T) => [keyMapper(val), val]) : null));
mapRef.current = new Map(values ? values.map((val: T) => [keyMapper(val), val]) : null);
update();
},
[setMap, keyMapper]
[mapRef, keyMapper, update]
);

return {
Expand Down

0 comments on commit ed1a42f

Please sign in to comment.