JAVASCRIPT
Implement a `useDebounce` Hook for Input Throttling
Create a custom React `useDebounce` hook to delay value updates, perfect for search inputs, API calls, and other performance-sensitive operations, preventing excessive re-renders.
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);
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` time has passed without the value changing. It uses `useState` to hold the debounced value and `useEffect` to set up and clear a `setTimeout`. Each time the `value` changes, the previous timeout is cleared, and a new one is set, ensuring the `debouncedValue` is only updated after the user pauses typing or the `value` stabilizes. This is crucial for optimizing performance in search bars or frequently triggered events.