Coding exercise: create a search box with debounce in React.
Model answer
Debounce means waiting until the user stops typing for a short time before doing the work. Put the delay in a small custom hook and clean up the timer so old values never fire.
function useDebounce(value, delay = 400) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}
function Search() {
const [q, setQ] = useState('');
const term = useDebounce(q);
useEffect(() => {
if (!term) return;
const ctrl = new AbortController();
fetch('/api/search?q=' + encodeURIComponent(term), { signal: ctrl.signal })
.then((r) => r.json()).then(console.log).catch(() => {});
return () => ctrl.abort();
}, [term]);
return <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search" />;
}The cleanup function clears the timer when the value changes, and AbortController cancels the older request so a slow response cannot overwrite a newer one.
Tips
- Explain debounce (wait until typing stops) versus throttle (at most once per interval).
Practise it yourself in the React and Angular code playground.
Learn this topic
React.js Full Course: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in React.
- Coding exercise: fetch API data and display it in a table in React.
- Coding exercise: implement pagination in React.
- Coding exercise: create a login form with validation in React.
- Coding exercise: build a parent-child communication example in React.
- Coding exercise: implement sorting and filtering in React.