UNPKG

@equinor/fusion-react-utils

Version:
35 lines 1.27 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ import { useLayoutEffect, useMemo, useRef } from 'react'; import { shallowEqual } from '../shallow-equal'; const noFns = {}; /** * Works lie `useProps` but will check if prop/function has changed before assignment * @param ref * @param functions * @param functionMap */ export const useElementFunctions = (ref, functions, functionMap) => { const fnsRef = useRef({}); const fns = useMemo(() => { /** early escaping no-op */ if (!functions || !functionMap) return noFns; // extract allowed functions const fns = [...functionMap.values()] .filter((k) => k in functions) .reduce((c, v) => Object.assign(c, { [v]: functions[v] }), {}); /** compare functions with existing */ const hasChanged = !shallowEqual(fnsRef.current, fns); return hasChanged ? fns : fnsRef.current; }, [fnsRef, functions, functionMap]); useLayoutEffect(() => { const obj = ref.current; if (!obj || !fns) return; for (const fnKey in fns) { obj[fnKey] = fns[fnKey]; } fnsRef.current = fns; }, [ref, fns, functionMap]); }; //# sourceMappingURL=useElementFunctions.js.map