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
- Controlled input with
querystate. debouncedQuery = useDebounce(query, 300).- Skip fetching for empty or very short queries.
- Fetch in an effect depending on
debouncedQuery, with anAbortControlleraborted in cleanup. - Track
status: idle, loading, success, error. - Render results, "no results" and error messages.
- 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
Mapin a ref, or TanStack Query withqueryKey: ["search", debouncedQuery]andplaceholderData: keepPreviousData). - Put the query in the URL (
?q=) so searches are shareable. - Accessibility:
role="search", a label, andaria-livefor the result count.
Code example
tsx
1import { useEffect, useState } from "react";23function 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}1112type Result = { id: number; title: string };13type Status = "idle" | "loading" | "success" | "error";1415export 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");2021 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 changes34 }, [debouncedQuery]);3536 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.