A custom React hook to debounce user input.
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;
}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;
}
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.
The useDebounce hook is a powerful tool to enhance UX by minimizing unnecessary updates and making your app feel smoother and more responsive.