1- import { type DependencyList , useMemo , useRef } from 'react' ;
1+ import { type DependencyList , useEffect , useMemo , useRef } from 'react' ;
22import { useUnmountEffect } from '../useUnmountEffect/index.js' ;
33
44export type DebouncedFunction < Fn extends ( ...args : any [ ] ) => any > = (
@@ -10,7 +10,8 @@ export type DebouncedFunction<Fn extends (...args: any[]) => any> = (
1010 * Makes passed function debounced, otherwise acts like `useCallback`.
1111 *
1212 * @param callback Function that will be debounced.
13- * @param deps Dependencies list when to update callback.
13+ * @param deps Dependencies list when to update callback. It also replaces invoked
14+ * callback for scheduled debounced invocations.
1415 * @param delay Debounce delay.
1516 * @param maxWait The maximum time `callback` is allowed to be delayed before
1617 * it's invoked. 0 means no max wait.
@@ -23,6 +24,7 @@ export function useDebouncedCallback<Fn extends (...args: any[]) => any>(
2324) : DebouncedFunction < Fn > {
2425 const timeout = useRef < ReturnType < typeof setTimeout > > ( ) ;
2526 const waitTimeout = useRef < ReturnType < typeof setTimeout > > ( ) ;
27+ const cb = useRef ( callback ) ;
2628 const lastCall = useRef < { args : Parameters < Fn > ; this : ThisParameterType < Fn > } > ( ) ;
2729
2830 const clear = ( ) => {
@@ -40,18 +42,23 @@ export function useDebouncedCallback<Fn extends (...args: any[]) => any>(
4042 // Cancel scheduled execution on unmount
4143 useUnmountEffect ( clear ) ;
4244
45+ useEffect ( ( ) => {
46+ cb . current = callback ;
47+ // eslint-disable-next-line react-hooks/exhaustive-deps
48+ } , deps ) ;
49+
4350 return useMemo ( ( ) => {
4451 const execute = ( ) => {
52+ clear ( ) ;
53+
4554 // Barely possible to test this line
4655 /* istanbul ignore next */
4756 if ( ! lastCall . current ) return ;
4857
4958 const context = lastCall . current ;
5059 lastCall . current = undefined ;
5160
52- callback . apply ( context . this , context . args ) ;
53-
54- clear ( ) ;
61+ cb . current . apply ( context . this , context . args ) ;
5562 } ;
5663
5764 const wrapped = function ( this , ...args ) {
0 commit comments