javascript 60 lines · 9 steps

Debounced search with cancellation in React

A custom hook delays input updates while AbortController cancels stale fetches, keeping search snappy and consistent.

Explained by highlit
1import { useState, useEffect, useMemo } from 'react';
2 
3function useDebounce(value, delay = 300) {
4 const [debounced, setDebounced] = useState(value);
5 
6 useEffect(() => {
7 const timer = setTimeout(() => setDebounced(value), delay);
8 return () => clearTimeout(timer);
9 }, [value, delay]);
10 
11 return debounced;
12}
13 
14export function SearchBox({ onResults }) {
15 const [query, setQuery] = useState('');
16 const debouncedQuery = useDebounce(query, 400);
17 const [results, setResults] = useState([]);
18 const [loading, setLoading] = useState(false);
19 
20 useEffect(() => {
21 const term = debouncedQuery.trim();
22 if (!term) {
23 setResults([]);
24 return;
25 }
26 
27 const controller = new AbortController();
28 setLoading(true);
29 
30 fetch(`/api/search?q=${encodeURIComponent(term)}`, { signal: controller.signal })
31 .then((res) => res.json())
32 .then((data) => {
33 setResults(data.items);
34 onResults?.(data.items);
35 })
36 .catch((err) => {
37 if (err.name !== 'AbortError') console.error(err);
38 })
39 .finally(() => setLoading(false));
40 
41 return () => controller.abort();
42 }, [debouncedQuery, onResults]);
43 
44 return (
45 <div className="search-box">
46 <input
47 type="search"
48 value={query}
49 placeholder="Search products…"
50 onChange={(e) => setQuery(e.target.value)}
51 />
52 {loading && <span className="spinner" aria-hidden />}
53 <ul>
54 {results.map((item) => (
55 <li key={item.id}>{item.name}</li>
56 ))}
57 </ul>
58 </div>
59 );
60}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Debouncing input prevents firing a request on every keystroke, cutting wasted network calls.
  2. 2Returning a cleanup function from useEffect cancels in-flight work before the next effect runs.
  3. 3AbortController plus an AbortError check avoids race conditions and noise from cancelled requests.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Debounced search with cancellation in React — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code