JAVASCRIPT
Implement a `useDebounce` Hook for Search Inputs
Optimize performance with `useDebounce`, a custom React hook that delays updating a value until a specified time has passed, ideal for search bars or expensive operations.
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 helps to delay the update of a value until a certain amount of time has passed without further changes. This is incredibly useful for scenarios like search inputs, where you don't want to trigger an API call on every keystroke. It uses `useState` to maintain the debounced value and `useEffect` to set up a `setTimeout`. Each time the `value` or `delay` changes, the previous timeout is cleared, and a new one is set, ensuring the `debouncedValue` only updates after the specified `delay` has elapsed since the last change.