import debounce from 'lodash/debounce'; import { useRef, useMemo, useEffect } from 'react'; type noop = (...args: any) => any; export interface DebounceOptions { wait?: number; leading?: boolean; trailing?: boolean; maxWait?: number; } const useDebounceFn = (fn: T, options?: DebounceOptions) => { const fnRef = useRef(fn); fnRef.current = fn; const wait = options?.wait ?? 1000; const debounced = useMemo( () => debounce( (...args: Parameters): ReturnType => { // @ts-ignore return fnRef.current?.(...args); }, wait, options ), [wait, options?.leading, options?.trailing, options?.maxWait] ); useEffect(() => { return () => { debounced.cancel(); }; }, [debounced]); return { run: debounced, cancel: debounced.cancel, flush: debounced.flush, }; }; export default useDebounceFn;