Back to results for “Hooks”
React › Custom Hooks

How would you build a custom hook that debounces a fast changing value, such as text typed into a search box?

Advanced

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.

Common 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?