Created
May 10, 2025 06:48
-
-
Save iamBijoyKar/6bcdbcda622b9a29d35a1070377e8c1b to your computer and use it in GitHub Desktop.
React Debounce Hook ( useDebounce )
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, useRef } from 'react' | |
/** | |
* A hook that returns a debounced version of the provided callback function | |
* @param callback The function to debounce | |
* @param delay The delay in milliseconds (default: 300ms) | |
* @returns A debounced version of the callback function | |
*/ | |
export function useDebounce<T extends (...args: any[]) => any>( | |
callback: T, | |
delay: number = 300 | |
): (...args: Parameters<T>) => void { | |
const timeoutRef = useRef<NodeJS.Timeout | null>(null) | |
return useCallback( | |
(...args: Parameters<T>) => { | |
if (timeoutRef.current) { | |
clearTimeout(timeoutRef.current) | |
} | |
timeoutRef.current = setTimeout(() => { | |
callback(...args) | |
}, delay) | |
}, | |
[callback, delay] | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment