-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update use-debounced-callback.ts to add a flush method to the returne…
…d callback as well as give an option to simply flush on unmount
- Loading branch information
Showing
2 changed files
with
86 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 31 additions & 6 deletions
37
packages/@mantine/hooks/src/use-debounced-callback/use-debounced-callback.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,44 @@ | ||
import { useCallback, useEffect, useRef } from 'react'; | ||
import { useCallbackRef } from '../use-callback-ref/use-callback-ref'; | ||
|
||
const noop = () => {}; | ||
|
||
export function useDebouncedCallback<T extends (...args: any[]) => any>( | ||
callback: T, | ||
delay: number | ||
options: number | { delay: number; flushOnUnmount?: boolean } | ||
) { | ||
const delay = typeof options === 'number' ? options : options.delay; | ||
const flushOnUnmount = typeof options === 'number' ? false : options.flushOnUnmount; | ||
const handleCallback = useCallbackRef(callback); | ||
const debounceTimerRef = useRef(0); | ||
useEffect(() => () => window.clearTimeout(debounceTimerRef.current), []); | ||
|
||
return useCallback( | ||
(...args: Parameters<T>) => { | ||
const lastCallback = Object.assign( | ||
useCallback( | ||
(...args: Parameters<T>) => { | ||
window.clearTimeout(debounceTimerRef.current); | ||
const flush = () => { | ||
if (debounceTimerRef.current !== 0) { | ||
debounceTimerRef.current = 0; | ||
handleCallback(...args); | ||
} | ||
}; | ||
lastCallback.flush = flush; | ||
debounceTimerRef.current = window.setTimeout(flush, delay); | ||
}, | ||
[handleCallback, delay] | ||
), | ||
{ flush: noop } | ||
); | ||
|
||
useEffect( | ||
() => () => { | ||
window.clearTimeout(debounceTimerRef.current); | ||
debounceTimerRef.current = window.setTimeout(() => handleCallback(...args), delay); | ||
if (flushOnUnmount) { | ||
lastCallback.flush(); | ||
} | ||
}, | ||
[handleCallback, delay] | ||
[lastCallback, flushOnUnmount] | ||
); | ||
|
||
return lastCallback; | ||
} |