ReactHooks
Build a useDebounce hook in React
A ten-line hook that stops your search box from firing a request on every keystroke.
Every keystroke in a search input triggers a state change. If each change calls an API, you get a flood of requests and a flickering UI. Debouncing waits until the user pauses before acting.
The hook
useDebounce.js
import { useState, useEffect } from "react";
export function useDebounce(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
Tip. The cleanup function is the important part: it cancels the previous timer whenever the value changes.
Use it by passing your input state through the hook and fetching only when the debounced value changes.