JAVASCRIPT
React Hook: useDebounce for Input Values
Learn how to create a custom React hook to debounce any value, useful for optimizing performance in search inputs or frequently updated fields by delaying updates.
import { useState, useEffect } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
export default useDebounce;
How it works: This `useDebounce` hook takes a value and a delay. It returns a debounced version of that value. Whenever the `value` changes, a new timeout is set. If `value` changes again before the delay expires, the previous timeout is cleared, and a new one is set. This ensures the `debouncedValue` is only updated after a specified `delay` has passed without the `value` changing, making it perfect for optimizing expensive operations like API calls on search input.