How would you build a custom hook that debounces a fast changing value, such as text typed into a search box?
Short answer
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.
Advertisement
AModel answer
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.
Likely follow-ups
- Why is clearing the timeout inside the cleanup function important for this hook to work correctly?
- How would you write a similar hook that throttles instead of debounces?
Related topics