Skip to content

Commit 63f897a

Browse files
committed
fix(useDebouncedCallback): wrap handler in useEventCallback so it's not stale
1 parent 75da843 commit 63f897a

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

src/useDebouncedCallback.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { useCallback, useMemo, useRef } from 'react'
22
import useTimeout from './useTimeout'
33
import useMounted from './useMounted'
4+
import useEventCallback from './useEventCallback'
45

56
export 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

170179
export default useDebouncedCallback

0 commit comments

Comments
 (0)