React › Custom Hooks
How would you build a custom hook that debounces a fast changing value, such as text typed into a search box?
AdvancedAnswer
A debounce hook waits until the user has stopped typing for a short period before updating the final value, avoiding unnecessary work, like sending a network request, on every single keystroke.
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
const debouncedSearch = useDebounce(searchText, 500);Real-world example A search feature waits until a user pauses typing for half a second before actually sending a request to the server, using a useDebounce hook to avoid firing a network request on every single keystroke.