JAVASCRIPT
Custom Hook for Debouncing Input Values
Implement a reusable React custom hook to debounce input values, delaying state updates until a user pauses typing, optimizing performance for search bars and forms.
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;
}
How it works: This `useDebounce` custom hook takes a value and a delay, returning a new value that only updates after the specified delay has passed without the original value changing. It's ideal for optimizing performance in input fields where frequent updates are costly, such as search bars or real-time validation, by preventing excessive re-renders or API calls.