JAVASCRIPT
Create a Custom useDebounce Hook for Input
Implement a reusable `useDebounce` custom hook in React to delay state updates from user input, optimizing performance for search bars and type-ahead features.
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;
}
// Example Usage in a component:
function SearchInput() {
const [searchTerm, setSearchTerm] = useState('');
const debouncedSearchTerm = useDebounce(searchTerm, 500); // 500ms delay
useEffect(() => {
if (debouncedSearchTerm) {
// Perform API call or heavy computation here
console.log("Searching for:", debouncedSearchTerm);
}
}, [debouncedSearchTerm]);
return (
<input
type="text"
placeholder="Search..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
);
}
export default SearchInput;
How it works: The `useDebounce` custom hook provides a way to delay updating a value until a certain time has passed without further changes. This is highly useful for optimizing performance in scenarios like search inputs, where you don't want to trigger an API request or expensive computation on every keystroke. It uses `useState` to hold the debounced value and `useEffect` with a `setTimeout` to manage the delay and cleanup.