-
Notifications
You must be signed in to change notification settings - Fork 580
/
useDebouncedCallback.ts
37 lines (30 loc) · 1.12 KB
/
useDebouncedCallback.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { type DependencyList, useCallback, useEffect, useRef } from 'react'
import debounce from 'lodash.debounce'
import { type GenericFunction } from './shared/types'
import useWillUnmount from './useWillUnmount'
export interface DebounceOptions {
leading?: boolean | undefined
maxWait?: number | undefined
trailing?: boolean | undefined
}
const defaultOptions: DebounceOptions = {
leading: false,
trailing: true
}
/**
* Accepts a function and returns a new debounced yet memoized version of that same function that delays
* its invoking by the defined time.
* If time is not defined, its default value will be 250ms.
*/
const useDebouncedCallback = <TCallback extends GenericFunction>
(fn: TCallback, dependencies?: DependencyList, wait: number = 600, options: DebounceOptions = defaultOptions) => {
const debounced = useRef(debounce<TCallback>(fn, wait, options))
useEffect(() => {
debounced.current = debounce(fn, wait, options)
}, [fn, wait, options])
useWillUnmount(() => {
debounced.current?.cancel()
})
return useCallback(debounced.current, dependencies ?? [])
}
export default useDebouncedCallback