Debouncing is a technique to limit the rate at which a function is executed — it ensures that a function runs only after a certain delay has passed since the last time it was invoked.
🔹 Why use Debouncing?
To prevent unnecessary function calls, especially in events like:
- Typing in a search box
- Resizing a window
- Scrolling
🔸 Example: Without Debouncing (calls on every keystroke)
<input type="text" onChange={(e) => search(e.target.value)} />
The search function is called on every key press = performance issue.
🔸 Example: With Debouncing
import { useState, useEffect } from "react";
function useDebounce(value, delay) {
const [debouncedVal, setDebouncedVal] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedVal(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedVal;
}
// Usage
function SearchComponent() {
const [input, setInput] = useState('');
const debouncedInput = useDebounce(input, 500); // delay: 500ms
useEffect(() => {
if (debouncedInput) {
console.log("API Call with:", debouncedInput);
// fetch API logic here
}
}, [debouncedInput]);
return <input onChange={(e) => setInput(e.target.value)} />;
}
✅ Key Points
- Debounce delays function execution.
- Useful to optimize performance.
- Often used in search inputs, form validation, and resize listeners.