React Developer interview question · Most asked
Write a custom React hook that debounces a value, and use it to search an API without race conditions.
Hands-on Asked in Frontend Engineer · Full Stack Engineer interviews
Summary
A useDebouncedValue hook stores the latest value after it has stopped changing for a delay. The search effect then
runs on the debounced value and cancels the previous request with an AbortController, so a slow earlier response
can't overwrite a newer one.
Longer Answer
Points to explain: the cleanup function clears the timer and aborts the fetch; ignore AbortError; in real apps
TanStack Query handles caching, cancellation and deduplication for you (queryKey: ["search", debounced]).
Example
import { useEffect, useState } from "react";
export function useDebouncedValue<T>(value: T, delay = 300): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
export function Search() {
const [query, setQuery] = useState("");
const [results, setResults] = useState<string[]>([]);
const debounced = useDebouncedValue(query);
useEffect(() => {
if (!debounced) return setResults([]);
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(debounced)}`, { signal: controller.signal })
.then((r) => r.json())
.then(setResults)
.catch((e) => { if (e.name !== "AbortError") console.error(e); });
return () => controller.abort();
}, [debounced]);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search" />
<ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>
</>
);
}
Key Points
- Timer cleanup on every change.
- AbortController cancels stale requests.
- Ignore AbortError.
- TanStack Query solves this in production code.
Explanation
What interviewers look for
Correct effect cleanup and awareness of race conditions.
More React Developer questions
- Explain React concept: keys in lists.
- Explain React concept: lifting state up.
- Explain React concept: props.
- Explain React concept: state.
- A React page with a long list becomes slow when typing in a search box. How do you find and fix the problem?
- Explain React concept: controlled vs uncontrolled inputs.
- Explain React concept: JSX.
- What does `useState` do and when should you use it?