Debounce a Search Input with useDebounce

Medium
Free
#Hooks

Create a custom React hook called useDebounce that returns a value which only updates after a given delay has passed with no further changes. This is the classic technique behind search-as-you-type inputs: instead of filtering or fetching on every keystroke, you wait until the user pauses, then react to the latest value. It keeps fast typists from triggering a burst of expensive work. The demo below renders a controlled search input and filters a list of fruits by the debounced query. The input itself updates immediately on every keystroke, but the value used for filtering lags behind by the delay, so the list only re-filters once typing settles.

Requirements

  • Implement a useDebounce(value, delay) hook that returns the debounced version of value.
  • The returned value must update only after delay milliseconds have elapsed with no further changes to value.
  • Use useEffect together with setTimeout, and clean up the pending timer with clearTimeout on every change so rapid updates reset the countdown.
  • Keep the input controlled: it must reflect each keystroke immediately while the debounced value lags behind.
  • Do not change the FRUITS list, the filtering logic, or the input markup.

Concepts you'll practice