Intermediate LevelReact JS & React 19
How do you build a custom useDebounce hook for search input optimization?
❓ Interview Prompt: Explain search input debouncing, `useDebounce` implementation, timer cleanup, and optimizing high-frequency API queries.
Debouncing delays executing an action until a specified delay time has passed since the last user keystroke, preventing spamming API requests on every character typed:
'useDebounce' Implementation:
Stores value in state and sets a 'setTimeout' inside 'useEffect' that updates the debounced value after a delay (e.g. 300ms), clearing the previous timer on every new keystroke.
Code Implementation Example
jsx
function useDebounce(value, delay = 300) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Clear previous timer on every new value keystroke!
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
// Usage:
const debouncedSearchTerm = useDebounce(searchTerm, 500);💡Building a custom useDebounce hook to throttle search input API calls.
🎯 Interview Key Takeaway
Use a custom useDebounce hook to delay state execution and prevent excessive API calls during rapid text input.
#useDebounce#Custom Hooks#Debounce#Intermediate
Back to all React JS & React 19 Questions→