Created
June 29, 2024 13:58
-
-
Save floatrx/8107738cea9d5fd43d1cbb867ebb6972 to your computer and use it in GitHub Desktop.
Debounce
This file contains hidden or 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
import { DEFAULT_DEBOUNCE_DELAY } from '@/config/const'; | |
/** | |
* Debounce function | |
* @param fn - function to debounce | |
* @param delay - delay in milliseconds | |
* @returns debounced function | |
*/ | |
export const debounce = <T extends AnyFn>( | |
fn: T, | |
delay: number = DEFAULT_DEBOUNCE_DELAY, | |
): ((...args: Parameters<T>) => void) => { | |
let timeoutId: NodeJS.Timeout; | |
return (...args: Parameters<T>) => { | |
clearTimeout(timeoutId); | |
timeoutId = setTimeout(() => fn(...args), delay); | |
}; | |
}; |
This file contains hidden or 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
import { useCallback } from 'react'; | |
import { DEFAULT_DEBOUNCE_DELAY } from '@/config/const'; | |
import { debounce } from '@/lib/timing/debounce'; | |
/** | |
* Debounce function (hook) | |
* NOTE: fn should be ignored in the deps array | |
* @param fn - function to debounce | |
* @param delay - delay in milliseconds | |
* @returns debounced function | |
*/ | |
export const useDebounce = <T extends AnyFn>(fn: T, delay: number = DEFAULT_DEBOUNCE_DELAY): T => { | |
// Use useCallback to return a memoized version of the debounced function | |
return useCallback(debounce(fn, delay), [delay]) as T; // eslint-disable-line | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment