Skip to the page

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.

The 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 this and 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

  1. Build a search box that calls an API as the user types.
  2. Results for an old query sometimes replace the new ones. Why? Fix it.
  3. Write debounce with cancel and flush.
  4. Debounce vs throttle: which here and why?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview