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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing input prevents firing a request on every keystroke, cutting wasted network calls.
- 2Returning a cleanup function from useEffect cancels in-flight work before the next effect runs.
- 3AbortController plus an AbortError check avoids race conditions and noise from cancelled requests.
Related explainers
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
javascript
function attachThousandSeparators(input, { locale = 'en-US' } = {}) { const formatter = new Intl.NumberFormat(locale); const groupSep = formatter.format(11111).replace(/\d/g, '')[0] || ','; const decimalSep = formatter.format(1.1).replace(/\d/g, '')[0] || '.';
Live thousand separators without losing the caret
dom
intl
caret-preservation
Advanced
8 steps
javascript
import { useReducer, useEffect } from "react"; const initialState = { status: "idle", data: null, error: null };
Building a data-fetching hook in React
custom-hooks
usereducer
data-fetching
Intermediate
9 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
javascript
import { useState, useEffect, useCallback } from 'react'; function getColumnCount(width) { if (width < 640) return 1;
A responsive column hook in React
custom-hooks
debouncing
responsive-design
Intermediate
7 steps
javascript
function initCharacterCounter(textarea, options = {}) { const maxLength = options.maxLength ?? 280; const warnThreshold = options.warnThreshold ?? 0.9;
A live character counter for textareas
dom
closures
accessibility
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/debounced-search-with-cancellation-in-react-explained-javascript-b31f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.