useDebounce Hook
April 19, 2025
When dealing with user input in forms or search fields, it's common to wait until the user has stopped typing before taking action, such as fetching data from an API. This is where a debounce function is useful.
Here's a simple useDebounce hook for React:
import { useEffect, useState } from 'react';
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
How It Works
- useState holds the debounced version of the value.
- useEffect sets a timer that updates the debounced value after the specified delay.
- If the input value changes before the delay completes, the previous timer is cleared.
- This ensures that the value is only updated once the user has stopped typing for the specified time.
Example Usage
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 500);
useEffect(() => {
if (debouncedSearch) {
// Trigger API call or filter logic
fetchData(debouncedSearch);
}
}, [debouncedSearch]);
This avoids firing API calls on every keystroke, improving performance and reducing load.
Use Cases
- Search input
- Filtering lists
- Waiting to trigger analytics events
- Delaying validation
Notes
- The delay is in milliseconds.
- Works for any type T, not just strings.
- Always make sure you handle cleanup to avoid memory leaks.
The useDebounce hook is a powerful tool to enhance UX by minimizing unnecessary updates and making your app feel smoother and more responsive.