@@ -20,64 +20,6 @@ type useDebouncedFunctionReturn<Args extends unknown[]> = Readonly<{
20
20
cancelDebounce : ( ) => void ;
21
21
} > ;
22
22
23
- /**
24
- * Creates a debounce function that is resilient to React re-renders, as well as
25
- * a function for canceling a pending debounce.
26
- *
27
- * The returned-out functions will maintain the same memory references, but the
28
- * debounce function will always "see" the most recent versions of the arguments
29
- * passed into the hook, and use them accordingly.
30
- *
31
- * If the debounce time changes while a callback has been queued to fire, the
32
- * callback will be canceled completely. You will need to restart the debounce
33
- * process by calling the returned-out function again.
34
- */
35
- export function useDebouncedFunction <
36
- // Parameterizing on the args instead of the whole callback function type to
37
- // avoid type contra-variance issues
38
- Args extends unknown [ ] = unknown [ ] ,
39
- > (
40
- callback : ( ...args : Args ) => void | Promise < void > ,
41
- debounceTimeMs : number ,
42
- ) : useDebouncedFunctionReturn < Args > {
43
- const timeoutIdRef = useRef < number | null > ( null ) ;
44
- const cancelDebounce = useCallback ( ( ) => {
45
- if ( timeoutIdRef . current !== null ) {
46
- window . clearTimeout ( timeoutIdRef . current ) ;
47
- }
48
-
49
- timeoutIdRef . current = null ;
50
- } , [ ] ) ;
51
-
52
- const debounceTimeRef = useRef ( debounceTimeMs ) ;
53
- useEffect ( ( ) => {
54
- cancelDebounce ( ) ;
55
- debounceTimeRef . current = debounceTimeMs ;
56
- } , [ cancelDebounce , debounceTimeMs ] ) ;
57
-
58
- const callbackRef = useRef ( callback ) ;
59
- useEffect ( ( ) => {
60
- callbackRef . current = callback ;
61
- } , [ callback ] ) ;
62
-
63
- // Returned-out function will always be synchronous, even if the callback arg
64
- // is async. Seemed dicey to try awaiting a genericized operation that can and
65
- // will likely be canceled repeatedly
66
- const debounced = useCallback (
67
- ( ...args : Args ) : void => {
68
- cancelDebounce ( ) ;
69
-
70
- timeoutIdRef . current = window . setTimeout (
71
- ( ) => void callbackRef . current ( ...args ) ,
72
- debounceTimeRef . current ,
73
- ) ;
74
- } ,
75
- [ cancelDebounce ] ,
76
- ) ;
77
-
78
- return { debounced, cancelDebounce } as const ;
79
- }
80
-
81
23
/**
82
24
* Takes any value, and returns out a debounced version of it.
83
25
*/
0 commit comments