Debounce and throttle are techniques to control how often a function is executed, especially for high-frequency events like typing, scrolling, or resizing. They improve performance and prevent unnecessary API calls or UI updates.
1️⃣ Debounce
- Definition: Ensures a function is executed only after a certain delay has passed since the last event.
- Use Case: Waiting until the user stops typing to make an API call (e.g., search input).
Example: Search Input with Debounce
import React, { useState, useEffect } from "react";
import { debounce } from "lodash";
function Search() {
const [query, setQuery] = useState("");
// Debounced API call
const fetchResults = debounce((searchTerm) => {
console.log("Fetching results for:", searchTerm);
// fetch API here
}, 500); // 500ms delay
useEffect(() => {
if (query) fetchResults(query);
// Cleanup to cancel pending debounce on unmount or query change
return () => fetchResults.cancel();
}, [query]);
return (
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}
export default Search;
Explanation:
- API call happens only after 500ms of no typing
- Prevents too many requests while user types rapidly
2️⃣ Throttle
- Definition: Ensures a function is executed at most once every specified time interval, regardless of how many times the event occurs.
- Use Case: Handling scroll, resize, or mouse move events efficiently.
Example: Scroll Event with Throttle
import React, { useEffect } from "react";
import { throttle } from "lodash";
function ScrollTracker() {
useEffect(() => {
const handleScroll = throttle(() => {
console.log("Scroll position:", window.scrollY);
}, 200); // execute at most once every 200ms
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return <div style={{ height: "2000px" }}>Scroll down</div>;
}
export default ScrollTracker;
Explanation:
handleScrollexecutes once every 200ms even if the user scrolls continuously- Reduces performance overhead
3️⃣ Summary of Use Cases
| Technique | When to Use | Example |
|---|---|---|
| Debounce | Execute after user stops performing action | Search input, autocomplete |
| Throttle | Execute at a fixed interval | Scroll events, window resize, mouse move |
⚡ Key Points:
- Both techniques improve performance in React apps
- Use lodash, underscore, or custom functions for debounce/throttle
- Always clean up listeners or cancel debounce in
useEffect