Overview
TheuseDebounce hook is a utility that delays updating a value until after a specified delay period has passed since the last change. This is particularly useful for optimizing performance in scenarios like search inputs, where you want to wait for the user to stop typing before triggering an API call.
Signature
Parameters
The value to debounce. Can be any type.
The delay in milliseconds to wait before updating the debounced value.
Return Value
Returns the debounced value of typeT. The returned value will only update after the specified delay has passed since the last change to the input value.
Usage Example
Fromsrc/components/Search.tsx:37:
How It Works
The hook usesuseState and useEffect to manage the debounced value:
- It maintains an internal state for the debounced value
- When the input value changes, it sets a timeout to update the debounced value after the specified delay
- If the value changes again before the delay expires, the previous timeout is cleared and a new one is set
- This ensures the debounced value only updates after the user has stopped changing the input for the specified delay period
Common Use Cases
- Search inputs: Wait for the user to finish typing before triggering a search API call
- Form validation: Delay validation until the user has stopped typing
- Auto-save: Wait for the user to pause editing before saving changes
- Resize handlers: Throttle window resize events to improve performance