Menu

Implement Custom useDebounce & useThrottle Hooks

Medium

Implement Custom useDebounce & useThrottle Hooks

MediumCategory: Custom HooksAcceptance: 78%

Problem Statement

In React applications, rapidly firing event handlers (such as typing into a search input or scrolling) can cause severe performance degradation and excessive API requests. Your task is to write a custom React hook `useDebounce(value, delay)` that delays updating a value until after a specified `delay` in milliseconds has elapsed since the last time the value was changed. Additionally, implement a `useThrottle(value, limit)` hook that ensures updates occur at most once every `limit` milliseconds.

Examples

Example 1:

Input: value = 'cloudvyn', delay = 500

Output: 'cloudvyn' (after 500ms)

Explanation: The returned debounced value will update to 'cloudvyn' 500ms after the user stops typing.

Example 2:

Input: value changes at 0ms, 100ms, 200ms with delay = 300ms

Output: Value updates at 500ms

Explanation: Each new value resets the 300ms timer. The debounced hook emits the final value 300ms after 200ms.

Constraints

  • 1 <= delay <= 5000 (milliseconds)
  • The hook must clean up previous timers using clearTimeout on value or delay changes.
  • Must return the latest debounced value without memory leaks.
Solution Editor
Loading...
Input:value = 'react', delay = 300
Expected Output:'react'