@orca-fe/hooks
Version:
React Hooks Collections
24 lines (23 loc) • 754 B
JavaScript
// Copy from ahooks@3
import { useMemo, useRef } from 'react';
function useMemorizedFn(fn) {
if (process.env.NODE_ENV === 'development') {
if (typeof fn !== 'function') {
console.error(`useMemorizedFn expected parameter is a function, got ${typeof fn}`);
}
}
var fnRef = useRef(fn);
// why not write `fnRef.current = fn`?
// https://github.com/alibaba/hooks/issues/728
fnRef.current = useMemo(() => fn, [fn]);
var memoizedFn = useRef();
if (!memoizedFn.current) {
memoizedFn.current = function (...args) {
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-invalid-this
return fnRef.current.apply(this, args);
};
}
return memoizedFn.current;
}
export default useMemorizedFn;