Skip to content

Instantly share code, notes, and snippets.

@iamBijoyKar
Created May 10, 2025 06:48
Show Gist options
  • Save iamBijoyKar/6bcdbcda622b9a29d35a1070377e8c1b to your computer and use it in GitHub Desktop.
Save iamBijoyKar/6bcdbcda622b9a29d35a1070377e8c1b to your computer and use it in GitHub Desktop.
React Debounce Hook ( useDebounce )
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