11import { useCallback , useMemo , useRef } from 'react'
22import useTimeout from './useTimeout'
33import useMounted from './useMounted'
4+ import useEventCallback from './useEventCallback'
45
56export interface UseDebouncedCallbackOptions {
67 wait : number
@@ -18,6 +19,9 @@ export interface UseDebouncedCallbackOptionsLeading
1819 * Creates a debounced function that will invoke the input function after the
1920 * specified wait.
2021 *
22+ * > Heads up! debounced functions are not pure since they are called in a timeout
23+ * > Don't call them inside render.
24+ *
2125 * @param fn a function that will be debounced
2226 * @param waitOrOptions a wait in milliseconds or a debounce configuration
2327 */
@@ -30,6 +34,9 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
3034 * Creates a debounced function that will invoke the input function after the
3135 * specified wait.
3236 *
37+ * > Heads up! debounced functions are not pure since they are called in a timeout
38+ * > Don't call them inside render.
39+ *
3340 * @param fn a function that will be debounced
3441 * @param waitOrOptions a wait in milliseconds or a debounce configuration
3542 */
@@ -49,6 +56,8 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
4956 const isTimerSetRef = useRef ( false )
5057 const lastArgsRef = useRef < unknown [ ] | null > ( null )
5158
59+ const handleCallback = useEventCallback ( fn )
60+
5261 const {
5362 wait,
5463 maxWait,
@@ -117,7 +126,7 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
117126 lastArgsRef . current = null
118127 lastInvokeTimeRef . current = time
119128
120- const retValue = fn ( ...args )
129+ const retValue = handleCallback ( ...args )
121130 returnValueRef . current = retValue
122131 return retValue
123132 }
@@ -164,7 +173,7 @@ function useDebouncedCallback<TCallback extends (...args: any[]) => any>(
164173
165174 return returnValueRef . current
166175 }
167- } , [ fn , wait , maxWait , leading , trailing ] )
176+ } , [ handleCallback , wait , maxWait , leading , trailing ] )
168177}
169178
170179export default useDebouncedCallback
0 commit comments