ReactMedium

Search with debounce

A debounced search keeps the input responsive by updating its value on every keystroke, but only fetches results after the user pauses (for example 300ms). Implement it with a useDebounce hook for the query, an effect (or TanStack Query) keyed on the debounced value, AbortController to cancel stale requests, and clear loading, empty and error states.

Steps

  1. Controlled input with query state.
  2. debouncedQuery = useDebounce(query, 300).
  3. Skip fetching for empty or very short queries.
  4. Fetch in an effect depending on debouncedQuery, with an AbortController aborted in cleanup.
  5. Track status: idle, loading, success, error.
  6. Render results, "no results" and error messages.
  7. Optional: show stale results dimmed while loading, highlight matched text, keyboard navigation of results.

Points to mention

  • Debouncing reduces requests; aborting prevents race conditions where an old response overwrites a newer one. You need both.
  • Encode the query with encodeURIComponent.
  • Cache recent results (a Map in a ref, or TanStack Query with queryKey: ["search", debouncedQuery] and placeholderData: keepPreviousData).
  • Put the query in the URL (?q=) so searches are shareable.
  • Accessibility: role="search", a label, and aria-live for the result count.

Code example

tsx
1import { useEffect, useState } from "react";
2
3function useDebounce<T>(value: T, delay: number) {
4 const [v, setV] = useState(value);
5 useEffect(() => {
6 const id = setTimeout(() => setV(value), delay);
7 return () => clearTimeout(id);
8 }, [value, delay]);
9 return v;
10}
11
12type Result = { id: number; title: string };
13type Status = "idle" | "loading" | "success" | "error";
14
15export function DebouncedSearch() {
16 const [query, setQuery] = useState("");
17 const debouncedQuery = useDebounce(query.trim(), 300);
18 const [results, setResults] = useState<Result[]>([]);
19 const [status, setStatus] = useState<Status>("idle");
20
21 useEffect(() => {
22 if (debouncedQuery.length < 2) {
23 setResults([]);
24 setStatus("idle");
25 return;
26 }
27 const controller = new AbortController();
28 setStatus("loading");
29 fetch(`https://dummyjson.com/products/search?q=${encodeURIComponent(debouncedQuery)}`, { signal: controller.signal })
30 .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
31 .then((data: { products: Result[] }) => { setResults(data.products); setStatus("success"); })
32 .catch((e) => e.name !== "AbortError" && setStatus("error"));
33 return () => controller.abort(); // cancel when the query changes
34 }, [debouncedQuery]);
35
36 return (
37 <div role="search">
38 <label htmlFor="q">Search products</label>
39 <input id="q" value={query} onChange={(e) => setQuery(e.target.value)} />
40 <p aria-live="polite">
41 {status === "loading" && "Searching…"}
42 {status === "error" && "Something went wrong."}
43 {status === "success" && `${results.length} results`}
44 </p>
45 <ul style={{ opacity: status === "loading" ? 0.6 : 1 }}>{results.map((r) => <li key={r.id}>{r.title}</li>)}</ul>
46 </div>
47 );
48}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app