FrontendInterviews.dev

Loading problem…

323. useDebounce Hook

Medium•

Build a reusable useDebounce hook for React that delays value updates until typing/input activity settles.

What You Need To Implement

Implement only this hook function:

function useDebounce<T>(value: T, delay: number): T

The rest of the starter app is already wired as a working demo UI.

Requirements

1. Debounce Behavior

  • Return the last stable value only after delay ms with no new updates
  • If value changes again before delay ends, reset the timer

2. Lifecycle Correctness

  • Clear previous timer when value or delay changes
  • Clear timer on unmount to avoid stale updates
  • Treat delay <= 0 as immediate update

3. How To Test In Provided UI

  • Type quickly in the search input (for example: a, aa, aar)
  • Confirm list filtering follows debounced value, not every keystroke
  • Change delay value in code (for example 350 -> 0) and verify behavior changes accordingly

Data Contract

export type UseDebounce = <T>(value: T, delay: number) => T

Constraints

  • Must cleanup pending timers on dependency change and unmount.
  • Must return generic value type without casting hacks.
  • Must not mutate incoming value.
  • Delay values <= 0 should behave like immediate pass-through.