JAVASCRIPT
Implement a Custom `useDebounce` React Hook
Create a `useDebounce` hook in React to delay execution of a function until a certain time has passed without further calls, optimizing performance for fast-firing events.
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('Searching 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: The `useDebounce` hook takes a value and a delay. It returns a debounced version of that value, which only updates after the specified delay has passed since the last change to the original value. This is highly effective for reducing the frequency of costly operations like API calls triggered by user input or resize events.