JAVASCRIPT
Efficiently Debounce State Updates with useDebounce Hook
Custom React hook `useDebounce` delays updating a state value until a specified time passes, optimizing performance for search inputs or frequent API calls.
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 hook takes a `value` and a `delay`. It maintains an internal `debouncedValue` state. Whenever the `value` changes, a timeout is set to update `debouncedValue` after the specified `delay`. If the `value` changes again before the timeout completes, the previous timeout is cleared and a new one is set, effectively delaying the update until the `value` has been stable for the `delay` duration. This is crucial for optimizing performance in scenarios like search bars to prevent excessive API calls.