JAVASCRIPT
Custom Hook: useDebounce for Delayed Value Updates
Implement a custom React hook, useDebounce, to delay updates of a value until a specified time has passed without further changes, perfect for search inputs.
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);
// // Effect for API call or other operations dependent on debouncedSearchTerm
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Fetching data for:', debouncedSearchTerm);
// // Call your API here
// } else {
// console.log('Search term cleared.');
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: The `useDebounce` hook provides a debounced version of any value. It updates the debounced value only after a specified `delay` has passed since the last change to the original `value`. This is highly useful for optimizing performance in scenarios like search inputs, preventing excessive API calls or computationally expensive operations until the user has finished typing.