JAVASCRIPT
Implement a useDebounce Hook for Input Delay
Create a custom React hook, `useDebounce`, to delay state updates or function calls, ideal for search inputs, preventing excessive API calls, or costly 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 SearchBar() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log("Fetching data for:", debouncedSearchTerm);
// // Perform API call or expensive operation 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 the value changing. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` to manage the delay. Each time the `value` changes, the previous timeout is cleared, and a new one is set. This is highly effective for optimizing performance in search bars, input validations, or any event that triggers frequently.