Function: useDebounce()
useDebounce<
T>(callback,delay): (...args) =>void
Defined in: use-debounce.ts:49
A custom React hook that debounce a function, ensuring it is only called after a specified delay has passed since the last invocation.
This hook is useful for optimizing performance in scenarios where frequent function calls need to be reduced, such as handling search input, resize events, or button clicks.
Type Parameters
T
T extends (...args) => void
The type of the callback function to debounce.
Parameters
callback
T
The function to be debounced.
delay
number
The debounce delay in milliseconds.
Returns
- A debounced version of the provided callback function.
(...args) => void
Examples
const [query, setQuery] = useState("");
const fetchData = (searchTerm: string) => {
console.log(`Fetching data for ${searchTerm}`);
};
const debouncedFetchData = useDebounce(fetchData, 300);
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
debouncedFetchData(event.target.value);
};
return <input type="text" value={query} onChange={handleInputChange} />;
const logMessage = (message: string) => {
console.log(message);
};
const debouncedLog = useDebounce(logMessage, 500);
return <button onClick={() => debouncedLog("Button clicked!")}>Click Me</button>;
For a live, editable example, see the useDebounce docs page.