Debouncing is a technique to limit how often a function is called.
- Useful when dealing with rapidly firing events, like
onChangefor a search input, window resizing, or scrolling. - The function executes only after a certain delay since the last call.
1️⃣ Debounce Function Implementation
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer); // clear previous timer
timer = setTimeout(() => { // set new timer
fn.apply(this, args);
}, delay);
};
}
fn→ function to debouncedelay→ wait time in millisecondsclearTimeoutensures only the last event triggersfn
2️⃣ Example: User Search Input
import React, { useState, useCallback } from "react";
function Search() {
const [query, setQuery] = useState("");
// Function to simulate API call
const fetchResults = (searchTerm) => {
console.log("Searching for:", searchTerm);
// Here you can call your API
};
// Debounced version of fetchResults
const debouncedFetch = useCallback(debounce(fetchResults, 500), []);
const handleChange = (e) => {
setQuery(e.target.value);
debouncedFetch(e.target.value);
};
return (
<div>
<input
type="text"
value={query}
onChange={handleChange}
placeholder="Search..."
/>
</div>
);
}
export default Search;
3️⃣ How It Works
- User types in the input →
handleChangeruns. debouncedFetchwaits 500ms after the last keystroke.- If the user types again before 500ms → previous timer is cleared.
- Only when typing stops for 500ms,
fetchResultsis executed.
✅ Prevents unnecessary API calls and improves performance.
4️⃣ Key Points
- Always wrap the debounced function in
useCallbackto avoid recreating it on every render. - Adjust delay based on use case (e.g., 300–500ms for search inputs).
- Works best for input fields, scroll events, or resize events.
In short:
Debounce ensures a function is called only after a pause in rapid events, preventing excessive calls, improving performance, and giving a smooth user experience.