0 day streak
javascript / intermediate
Snippet

Implementing Debounced Search

Debouncing delays the execution of a function until after a specific amount of time has passed since the last trigger, reducing unnecessary API calls.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
const [searchTerm, setSearchTerm] = useState('');
const [debouncedTerm, setDebouncedTerm] = useState('');
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedTerm(searchTerm);
}, 500);
return () => clearTimeout(timer);
}, [searchTerm]);
react
Breakdown
1
const timer = setTimeout(...)
Sets a delay before updating the final search term.
2
return () => clearTimeout(timer)
Cancels the previous timer if the user types again before the delay ends.
3
[searchTerm]
The effect dependency ensures the timer restarts on every keystroke.