import { debounce } from 'lodash'
import { useMemo } from 'react'
import { useUnmount } from 'react-use'
import { useLatest } from './useLatest'
type DebounceOptions = {
wait?: number
leading?: boolean
trailing?: boolean
maxWait?: number
}
type useDebounceFnRetrunProps = {
run: () => void
cancel: () => void
flush: () => void
}
export const useDebounceFn = (
fn: Function,
options?: DebounceOptions
): useDebounceFnRetrunProps => {
const fnRef = useLatest(fn)
const wait = options?.wait ?? 1000
const debounced = useMemo(
() =>
debounce(
(...args) => {
return fnRef.current(...args)
},
wait,
options
),
[]
)
useUnmount(() => {
debounced.cancel()
})
return {
run: debounced,
cancel: debounced.cancel,
flush: debounced.flush,
}
}