Simple React SearchInput component that uses debouncing with a 300ms delay to trigger search logic.
✅ SearchInput with Debounce (300ms)
import { useState, useEffect } from "react";
function SearchInput() {
const [query, setQuery] = useState("");
const [debouncedQuery, setDebouncedQuery] = useState("");
// Debounce logic
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedQuery(query);
}, 300); // 300ms delay
return () => clearTimeout(timer);
}, [query]);
// Simulated search
useEffect(() => {
if (debouncedQuery) {
console.log("Searching for:", debouncedQuery);
// API call goes here
}
}, [debouncedQuery]);
return (
<input
type="text"
placeholder="Search..."
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
);
}
export default SearchInput;
🧠 How It Works
- User types →
queryupdates immediately - Debounce waits 300ms after typing stops
debouncedQueryupdates once- Search logic runs only once per pause, not on every keystroke
🎯 Short Interview Answer
Debouncing delays the execution of a search until the user stops typing for a specified time. In React, this is commonly implemented using
useEffectandsetTimeoutwith cleanup.
⭐ One-line summary
Debouncing prevents unnecessary API calls by delaying search execution until typing stops.