JAVASCRIPT
Debouncing User Input with a `useDebounce` Hook
Implement a `useDebounce` custom hook in React to delay updating a value until a specified time has passed, optimizing performance for frequent input changes.
import { useState, useEffect } from 'react';
/**
* Custom hook to debounce a value.
* @param {any} value The value to debounce.
* @param {number} delay The debounce delay in milliseconds.
* @returns {any} The debounced value.
*/
export function useDebounce(value, delay) {
// State to store the debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
// Set a timeout to update the debounced value after the delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Clear the timeout if value changes (or component unmounts)
// This ensures the timer is reset if the value changes rapidly
return () => {
clearTimeout(handler);
};
}, [value, delay]); // Re-run effect if value or delay changes
return debouncedValue;
}
// Example Usage:
// function SearchInput() {
// const [searchTerm, setSearchTerm] = useState('');
// const debouncedSearchTerm = useDebounce(searchTerm, 500);
// // Effect for API call (will only run after debouncedSearchTerm changes)
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Fetching data for:', debouncedSearchTerm);
// // Make API call here
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: The `useDebounce` custom hook is designed to delay updating a state variable until a certain amount of time has passed since the last change. This is incredibly useful for optimizing performance in scenarios like search inputs, where you don't want to trigger an expensive operation (e.g., an API call) on every keystroke. It uses `useState` to hold the debounced value and `useEffect` with a cleanup function to manage the timer.