JAVASCRIPT
Creating a useDebounce Custom Hook for Input Fields
Implement a reusable React `useDebounce` hook to delay execution of a function or state update until after a specified time, perfect for search inputs and performance optimization.
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);
// useEffect(() => {
// if (debouncedSearchTerm) {
// console.log('Searching for:', debouncedSearchTerm);
// // Perform API call or other expensive operation
// }
// }, [debouncedSearchTerm]);
// return (
// <input
// type="text"
// placeholder="Search..."
// value={searchTerm}
// onChange={(e) => setSearchTerm(e.target.value)}
// />
// );
// }
How it works: This custom `useDebounce` hook takes a value and a delay (in milliseconds) as arguments. It maintains an internal state `debouncedValue` which only updates after the specified delay has passed since the last change to the input `value`. It uses `useEffect` to set a timeout that updates `debouncedValue`. The cleanup function in `useEffect` ensures that any pending timeout is cleared if the `value` changes before the delay is complete, preventing unnecessary executions and ensuring only the last input triggers the action after the debounce period.