JAVASCRIPT
Create a `useDebounce` Custom Hook in React
Learn to build a `useDebounce` custom React hook to delay executing a function until after a certain time, preventing excessive re-renders or API calls.
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 here
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: This custom hook debounces a value, meaning it delays updating the `debouncedValue` state until a specified `delay` has passed since the last change to the `value`. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` to manage the delay. The cleanup function of `useEffect` (`clearTimeout`) is crucial to cancel the previous timer if the value changes before the delay completes, ensuring only the last input triggers the update.