UNPKG

@lesnoypudge/utils-react

Version:

lesnoypudge's utils-react

48 lines (47 loc) 1.67 kB
import { pick, shallowEqual } from "@lesnoypudge/utils"; import { useContextSelector } from "@fluentui/react-context-selector"; import { useConst } from "../../../../hooks/useConst/useConst.js"; import { useFunction } from "../../../../hooks/useFunction/useFunction.js"; import { useRef, useMemo } from "react"; const EMPTY_VALUE = {}; const useContextProxy = (context) => { const usedKeys = useConst(() => /* @__PURE__ */ new Set()); const prevSelectedValueRef = useRef(EMPTY_VALUE); const selector = useFunction((value2) => { if (value2 === void 0) return value2; const prev = prevSelectedValueRef; if (prev.current === EMPTY_VALUE) { prev.current = value2; return value2; } if (usedKeys.size === 0) { return prev.current; } const usedKeysList = [...usedKeys.values()]; const newUsedValue = pick(value2, ...usedKeysList); const prevUsedValue = pick(prev.current, ...usedKeysList); if (shallowEqual(newUsedValue, prevUsedValue)) { return prev.current; } prev.current = value2; return value2; }); const value = useContextSelector(context, selector); const proxyHandler = useConst(() => ({ get: (target, propertyKey, receiver) => { if (Object.hasOwn(target, propertyKey) && typeof propertyKey === "string") { usedKeys.add(propertyKey); } return Reflect.get(target, propertyKey, receiver); } })); const memoizedValue = useMemo(() => { if (value === void 0) return value; return new Proxy(value, proxyHandler); }, [value, proxyHandler]); return memoizedValue; }; export { useContextProxy }; //# sourceMappingURL=useContextProxy.js.map