1
1
import { useCallback , useMemo , useRef } from 'react'
2
2
import useTimeout from './useTimeout'
3
3
import useMounted from './useMounted'
4
+ import useEventCallback from './useEventCallback'
4
5
5
6
export interface UseDebouncedCallbackOptions {
6
7
wait : number
@@ -18,6 +19,9 @@ export interface UseDebouncedCallbackOptionsLeading
18
19
* Creates a debounced function that will invoke the input function after the
19
20
* specified wait.
20
21
*
22
+ * > Heads up! debounced functions are not pure since they are called in a timeout
23
+ * > Don't call them inside render.
24
+ *
21
25
* @param fn a function that will be debounced
22
26
* @param waitOrOptions a wait in milliseconds or a debounce configuration
23
27
*/
@@ -30,6 +34,9 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
30
34
* Creates a debounced function that will invoke the input function after the
31
35
* specified wait.
32
36
*
37
+ * > Heads up! debounced functions are not pure since they are called in a timeout
38
+ * > Don't call them inside render.
39
+ *
33
40
* @param fn a function that will be debounced
34
41
* @param waitOrOptions a wait in milliseconds or a debounce configuration
35
42
*/
@@ -49,6 +56,8 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
49
56
const isTimerSetRef = useRef ( false )
50
57
const lastArgsRef = useRef < unknown [ ] | null > ( null )
51
58
59
+ const handleCallback = useEventCallback ( fn )
60
+
52
61
const {
53
62
wait,
54
63
maxWait,
@@ -117,7 +126,7 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
117
126
lastArgsRef . current = null
118
127
lastInvokeTimeRef . current = time
119
128
120
- const retValue = fn ( ...args )
129
+ const retValue = handleCallback ( ...args )
121
130
returnValueRef . current = retValue
122
131
return retValue
123
132
}
@@ -164,7 +173,7 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
164
173
165
174
return returnValueRef . current
166
175
}
167
- } , [ fn , wait , maxWait , leading , trailing ] )
176
+ } , [ handleCallback , wait , maxWait , leading , trailing ] )
168
177
}
169
178
170
179
export default useDebouncedCallback
0 commit comments