Hooks
useDebounce
A hook that delays the updating of a value until a specified time has passed since the last update.
useDebounce
The useDebounce
hook delays the updating of a value until a specified time has passed since the last update. This is useful for reducing the frequency of updates in scenarios like:
- Search inputs to avoid making API calls on every keystroke
- Form inputs that trigger expensive calculations
- Window resize events that should only trigger updates after the user has finished resizing
Raw Value:
Debounced Value:
Installation
Install the useDebounce hook using:
File Structure
use-debounce.ts
Parameters
Prop | Type | Default |
---|---|---|
value | T (generic type) | Required |
delay | number | 500 |
Return Value
Prop | Type | Default |
---|---|---|
debouncedValue | T (same type as the input value) | - |
Examples
Search with Debounce
A common use case for debouncing is with search inputs, where you want to avoid making API calls on every keystroke.
Start typing to search
Enter a search term
Resize Event Debouncing
Window resize events can fire rapidly during resizing, so debouncing helps optimize performance.
Use Cases
- Search Inputs: Reduce API calls while typing
- Form Validation: Delay validation until the user stops typing
- Auto-Save: Wait until the user finishes typing before saving
- Resize Handlers: Optimize performance during window resizing
- Scroll Events: Process scroll events less frequently for performance
- Filter/Sort Operations: Delay expensive data operations until user input is stable
Accessibility
This hook doesn’t directly impact accessibility, but proper use can improve user experience by reducing UI jank and ensuring responsive interfaces.
Best Practices
- Choose an appropriate delay based on the use case (typically 300-500ms for typing)
- Use debouncing for expensive operations that don’t need to run on every input change
- Consider providing visual feedback when debouncing causes a noticeable delay
- For immediate UI updates with debounced processing, maintain both the raw and debounced values