FrontendInterviews.dev

Loading problem…

324. useThrottle Hook

Medium•

Build a useThrottle hook that limits how often a rapidly changing value updates consumers.

What You Need To Implement

Implement only this hook function:

function useThrottle<T>(value: T, wait: number): T

The starter app already contains the full demo UI and interaction flow.

Requirements

1. Throttle Semantics

  • Emit first update immediately (leading behavior)
  • During throttle window, do not emit every intermediate value
  • Emit latest pending value at trailing edge

2. Lifecycle

  • Clear trailing timer on unmount
  • If wait <= 0, behave like pass-through (no throttling)

3. How To Test In Provided UI

  • Click Fire 5 rapid updates multiple times quickly
  • Verify Raw increases immediately and faster than Throttled
  • Verify Throttled eventually catches latest pending value
  • Set wait to 0 and verify both values track the same updates

Constraints

  • Must preserve latest pending value for trailing emission.
  • Must cleanup timers on unmount.
  • Must support generic value type.
  • wait <= 0 should disable throttling behavior.