JAVASCRIPT
Implement a Debounce Hook for Input Throttling
Optimize input performance and prevent excessive re-renders with a custom React `useDebounce` hook, ideal for search bars and real-time validation.
import { useState, useEffect } from 'react';
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
// Example usage:
/*
function SearchInput() {
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay
useEffect(() => {
if (debouncedSearchTerm) {
console.log('Fetching data for:', debouncedSearchTerm);
// Perform API call or heavy computation here
}
}, [debouncedSearchTerm]);
return (
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
*/
How it works: This `useDebounce` hook delays updating a value until a specified `delay` has passed without any further updates to the `value`. It uses `useState` to hold the debounced value and `useEffect` to set up and clear a `setTimeout`. Each time the `value` changes, the previous timer is cleared and a new one is set, ensuring the `debouncedValue` only updates after the user stops typing for the specified duration.