2022-03-09 14:59:24 +01:00
|
|
|
import { useState, useCallback, useRef, useMemo } from 'react';
|
|
|
|
|
2023-12-20 15:36:23 +01:00
|
|
|
export interface IUseWeakMap<K, V> {
|
2022-03-09 14:59:24 +01:00
|
|
|
set: (k: K, v: V) => void;
|
|
|
|
get: (k: K) => V | undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
// A WeakMap associates extra data with an object instance.
|
|
|
|
// This hook encapsulates a WeakMap, and will trigger
|
|
|
|
// a rerender whenever `set` is called.
|
|
|
|
export const useWeakMap = <K extends object, V>(
|
2023-10-02 14:25:46 +02:00
|
|
|
initial?: WeakMap<K, V>,
|
2022-03-09 14:59:24 +01:00
|
|
|
): IUseWeakMap<K, V> => {
|
|
|
|
const ref = useRef(initial ?? new WeakMap<K, V>());
|
|
|
|
const [, setState] = useState(0);
|
|
|
|
|
|
|
|
const set = useCallback((key: K, value: V) => {
|
|
|
|
ref.current.set(key, value);
|
2023-10-02 14:25:46 +02:00
|
|
|
setState((prev) => prev + 1);
|
2022-03-09 14:59:24 +01:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
const get = useCallback((key: K) => {
|
|
|
|
return ref.current.get(key);
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return useMemo(
|
|
|
|
() => ({
|
|
|
|
set,
|
|
|
|
get,
|
|
|
|
}),
|
2023-10-02 14:25:46 +02:00
|
|
|
[set, get],
|
2022-03-09 14:59:24 +01:00
|
|
|
);
|
|
|
|
};
|