useDebounce
A custom React hook for debouncing function calls
useDebounce returns a stable callback that postpones execution until no new call has occurred during the configured delay.
Each invocation clears the previous timer before scheduling a new one. The callback and delay are captured with React's dependency model, so changing either produces a new debounced function.
Installation
CLI
npx shadcn add https://ui.tiesen.id.vn/r/use-debounce.jsonManual
Copy and paste the following code into your project.
import * as React from 'react'const useDebounce = <T>(callback: (...args: T[]) => void, delay: number) => { const timeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(null) const debouncedCallback = React.useCallback( (...args: T[]) => { if (timeoutRef.current) clearTimeout(timeoutRef.current) // oxlint-disable-next-line promise/prefer-await-to-callbacks timeoutRef.current = setTimeout(() => callback(...args), delay) }, [callback, delay] ) return debouncedCallback}export { useDebounce }Usage
import { useState } from 'react'
import { useDebounce } from '@/hooks/use-debounce'
export function SearchInput() {
const [query, setQuery] = useState('')
const search = useDebounce((value: string) => {
console.log('Searching for:', value)
}, 300)
return (
<input
value={query}
onChange={(event) => {
const value = event.target.value
setQuery(value)
search(value)
}}
/>
)
}Behavior
useDebounce delays every call independently:
search('a')
search('ab')
search('abc')Only the final call executes when the 300 ms delay completes, provided no newer call replaces it.
The hook does not return a cancel method. If you need cancellation outside the next invocation, keep the behavior in your own effect or use a different abstraction.
API Reference
useDebounce
function useDebounce<T>(
callback: (...args: T[]) => void,
delay: number
): (...args: T[]) => void| Parameter | Description |
|---|---|
callback | Function executed after the debounce window expires. |
delay | Delay in milliseconds. |
The returned function accepts the same argument tuple as callback.