As asked
Write a useDebounce hook in TypeScript that delays a value update by a configurable ms. Then show how you would use it in a search screen that fires an API call only after the user stops typing for 300ms. Also handle the case where the component unmounts before the debounce fires.
Sample answer outline
The hook uses useState and useEffect: on value change it sets a setTimeout and returns the previous debouncedValue until the timeout fires. The useEffect cleanup cancels the timeout on unmount or re-run, preventing state updates on unmounted components. In the search screen, useDebounce wraps the raw query string and the API call is triggered by the debounced value in a separate useEffect. A strong answer also mentions cancelling in-flight fetch calls with AbortController when a new debounced query arrives.
Reference implementation (typescript)
function useDebounce<T>(value: T, delay: number): T {
const [debounced, setDebounced] = React.useState(value);
React.useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
// Usage in SearchScreen
const debouncedQuery = useDebounce(query, 300);
React.useEffect(() => {
if (!debouncedQuery) return;
const controller = new AbortController();
fetchResults(debouncedQuery, controller.signal);
return () => controller.abort();
}, [debouncedQuery]);Expect these follow-ups
- How do you test this hook in Jest with fake timers?
- How would you change this to throttle instead of debounce?