/** * fork from https://github.com/alibaba/hooks/blob/master/packages/hooks/src/useMemoizedFn/index.ts */ import { useMemo, useRef } from 'react' type noop = (this: any, ...args: any[]) => any type PickFunction = ( this: ThisParameterType, ...args: Parameters ) => ReturnType export default function useMemoizedFn(fn: T) { const fnRef = useRef(fn) const memoizedFn = useRef>() // why not write `fnRef.current = fn`? // https://github.com/alibaba/hooks/issues/728 fnRef.current = useMemo(() => fn, [fn]) if (!memoizedFn.current) { memoizedFn.current = function (this, ...args) { return fnRef.current.apply(this, args) } } return memoizedFn.current as T }