Creating a smooth, performant search experience in React requires avoiding excessive re-renders and API calls. Debouncing is a technique that delays function execution until a specified delay has passed. In this guide, you'll learn how to implement a fully debounced search bar using React’s built-in hooks—no external libraries required.
1. What Is Debouncing?
Debouncing ensures that a function is called only after a specified time has passed since it was last invoked. This is especially useful when triggering a search API call during typing.
2. The Core Concept
Here’s the key idea using useEffect
and setTimeout
:
import React, { useState, useEffect } from 'react';
function DebouncedSearch() {
const [query, setQuery] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState(query);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedQuery(query);
}, 500);
return () => {
clearTimeout(handler);
};
}, [query]);
useEffect(() => {
if (debouncedQuery) {
fetchResults(debouncedQuery);
}
}, [debouncedQuery]);
const fetchResults = async (searchTerm) => {
console.log("Fetching results for:", searchTerm);
// Simulate API call
};
return (
<input
type="text"
placeholder="Search..."
value={query}
onChange={(e) => setQuery(e.target.value)}
className="border px-4 py-2 rounded"
/>
);
}
export default DebouncedSearch;
3. Pros & Cons of Manual Debouncing
-
✅ Pros:
- No external dependencies
- Easy to understand and customize
- Fine-grained control over delay logic
-
⚠️ Cons:
- Repetitive code if used often
- Manual error handling and cancellation needed for API calls
Alternatives
- lodash.debounce: A popular utility for standardized debouncing logic
- React Query: Handles caching, debouncing, and stale data intelligently
- Custom hooks: Extract the debouncing logic for reuse
Conclusion
Implementing a debounced search manually helps you gain deeper control over performance and behavior. As your app grows, you may extract this logic into a custom hook or adopt utility libraries to keep code DRY and maintainable.
For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:
Using React Portals Like a Pro.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)