1- import { useCallback , useRef } from "react" ;
1+ import { useCallback , useEffect , useRef } from "react" ;
22
33// this function will directly trigger function if action is not currently executing.
44// if there are executing actions, it will delay the execution
@@ -10,6 +10,11 @@ export const useDebounceWithStatus = <F extends (...args: any[]) => any>(
1010) : [ F ] => {
1111 const timeoutRef = useRef < ReturnType < typeof setTimeout > | null > ( null ) ;
1212 const pendingActions = useRef < Parameters < F > > ( ) ;
13+ const canRun = useRef ( isExecuting ) ;
14+
15+ useEffect ( ( ) => {
16+ canRun . current = isExecuting ;
17+ } , [ isExecuting ] ) ;
1318
1419 const abort = useCallback ( ( ) : void => {
1520 if ( timeoutRef . current !== null ) {
@@ -21,7 +26,7 @@ export const useDebounceWithStatus = <F extends (...args: any[]) => any>(
2126 const runPendingActions = useCallback ( ( ) => {
2227 abort ( ) ;
2328 timeoutRef . current = setTimeout ( ( ) => {
24- if ( isExecuting ) {
29+ if ( canRun . current ) {
2530 runPendingActions ( ) ;
2631 } else {
2732 // only run the last action
@@ -33,18 +38,18 @@ export const useDebounceWithStatus = <F extends (...args: any[]) => any>(
3338 }
3439 }
3540 } , waitFor ) ;
36- } , [ abort , func , waitFor , isExecuting ] ) ;
41+ } , [ abort , func , waitFor ] ) ;
3742
3843 const debounced = useCallback (
3944 ( ...args : Parameters < F > ) : void => {
40- if ( isExecuting ) {
45+ if ( canRun . current ) {
4146 pendingActions . current = args ;
4247 runPendingActions ( ) ;
4348 } else {
4449 func ( ...args ) ;
4550 }
4651 } ,
47- [ runPendingActions , func , isExecuting ]
52+ [ runPendingActions , func ]
4853 ) ;
4954 return [ debounced as F ] ;
5055} ;
0 commit comments