UNPKG

ahooks

Version:
23 lines (22 loc) 732 B
import { useMemo, useRef } from 'react'; import { isFunction } from '../utils'; import isDev from '../utils/isDev'; const useMemoizedFn = (fn) => { if (isDev) { if (!isFunction(fn)) { console.error(`useMemoizedFn expected parameter is a function, got ${typeof fn}`); } } const fnRef = useRef(fn); // why not write `fnRef.current = fn`? // https://github.com/alibaba/hooks/issues/728 fnRef.current = useMemo(() => fn, [fn]); const memoizedFn = useRef(undefined); if (!memoizedFn.current) { memoizedFn.current = function (...args) { return fnRef.current.apply(this, args); }; } return memoizedFn.current; }; export default useMemoizedFn;