Overview
TheuseDebounce hook delays updating a value until after a specified delay has passed since the last change. This is particularly useful for search inputs, where you want to wait for the user to finish typing before making an API call.
Usage
Parameters
The value to debounce. Typically a state variable that changes frequently (e.g., user input).
The delay in milliseconds to wait before updating the debounced value. Common values:
300- Quick debounce for responsive UIs500- Standard debounce for search inputs1000- Longer debounce for expensive operations
Return Value
The debounced value that updates only after the specified delay has passed since the last change to
value.Type Signature
How It Works
- The hook creates internal state for the debounced value
- When
valuechanges, it sets a timer fordelaymilliseconds - If
valuechanges again before the timer expires, the timer is cleared and a new one is created - When the timer expires without interruption, the debounced value is updated
- The cleanup function ensures timers are cleared when the component unmounts
Common Use Cases
Search Input
Delay API calls until the user stops typing:Form Validation
Validate input after user pauses:Auto-Save
Save changes after user stops editing:Performance Benefits
- Reduces API calls: Instead of calling the API on every keystroke, wait until the user finishes typing
- Improves performance: Prevents unnecessary re-renders and computations
- Better UX: Reduces server load and potential rate limiting issues
Implementation
The hook uses React’suseState and useEffect to manage the debounced value:
