JAVASCRIPT
Custom useDebounce Hook for React
Create a reusable React hook to debounce any value, preventing excessive re-renders or API calls. Ideal for search inputs, window resizing, and event handling.
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: The `useDebounce` hook delays updating a value until a specified time has passed without further changes. It uses `useState` to hold the debounced value and `useEffect` with `setTimeout` to manage the delay. Each time the `value` or `delay` changes, the previous timeout is cleared, and a new one is set, ensuring the debounced value only updates after the specified `delay` has elapsed since the last change to `value`.