Search, lists and data · core
Debounced search with race-condition handling
A search box waits until the user pauses typing (debounce), cancels the previous request with AbortController, ignores any response that is not for the latest query, cleans up when the component unmounts, and shows loading, empty and error states.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Debounce 250–300 ms: each keystroke resets a timer; only the last call runs. Keep the input itself instant (controlled value), debounce only the fetch.
- Race conditions: responses can come back in any order ('lap' after 'laptop'). Abort the previous fetch with AbortController and ignore AbortError; ALSO guard with a request id or an 'ignore' flag in the effect cleanup, because some promises can't be aborted.
- useEffect pattern: const ctrl = new AbortController(); fetch(url, { signal: ctrl.signal }) …; return () => ctrl.abort(); — the cleanup runs before the next effect and on unmount.
- Empty query: clear results without a request. Trim and lower-case the query; set a minimum length.
- States: loading (keep old results dimmed rather than flashing empty), empty ('No results for "x"'), error with Retry.
- Cache results by query in a Map (optionally with TTL) so Backspace doesn't refetch.
- Timeouts: AbortSignal.timeout(ms), combined with the user's signal using AbortSignal.any (Baseline since March 2024).
- A debounce helper should keep
thisand arguments, and offer cancel() and flush().
The red pen
Common traps: mistake → fix
Mistake: Debounce the input's value itself
Fix: typing feels laggy.
Mistake: Create the debounced function inside render without useMemo/useRef
Fix: a new timer every render, so nothing is debounced.
Mistake: Only AbortController
Fix: a cached or non-abortable promise can still set stale results.
Mistake: No cleanup
Fix: setState after unmount and stale results.
Easy to hard
Questions interviewers ask, easy to hard
- Build a search box that calls an API as the user types.
- Results for an old query sometimes replace the new ones. Why? Fix it.
- Write debounce with cancel and flush.
- Debounce vs throttle: which here and why?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.