import debounce from "lodash.debounce"; import { useRef } from 'react'; import { useCreation } from '..'; import { DebounceOptions } from '../useDebounce/debounceOptions'; type Fn = (...args: any) => any; interface ReturnValue { run: T; cancel: () => void; } function useDebounceFn(fn: T, options?: DebounceOptions): ReturnValue { const fnRef = useRef(fn); fnRef.current = fn; const wait = options?.wait ?? 1000; const debounced = useCreation( () => debounce( (...args: any) => { fnRef.current(...args); }, wait, options, ), [], ); return { run: (debounced as any) as T, cancel: debounced.cancel, }; } export default useDebounceFn;