Loading content…
Loading content…
Implement an input debouncing function in React and TypeScript. When a user typing in a search bar modifies the query value, delay the remote API fetch operation by 300ms. If they type again before the timeout expires, cancel the pending action.
Expected Output
A reusable React hook `useDebounce` and search input component demonstrating API call throttling.
Click to toggle the recommended code solution
Architectural Explanation
The custom `useDebounce` hook registers a setTimeout buffer. It relies on useEffect's standard return cleanup loop to abort pending timers, preventing concurrent API requests during active typing.Code Snippet
import { useState, useEffect } from "react";
export function useDebounce<T>(value: T, delay = 300): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}How to pitch this solution during technical interviews
I prevent request flooding by implementing a useDebounce hook. It registers a timeout inside useEffect to update a debounced value state. If the monitored dependency updates before the timer finishes, the cleanup function fires and kills the pending timer.