In React applications, user interactions such as typing in an input field, scrolling, or resizing the window can trigger events very frequently. If these events cause expensive operations like API calls, filtering large data sets, or heavy computations, performance can degrade quickly. Debouncing and throttling are techniques used to control how often these operations are executed.
Debouncing Inputs
Debouncing ensures that a function runs only after a certain period of inactivity. This means the function executes only when the user stops typing or interacting for a specified amount of time. Debouncing is ideal for search inputs, autocomplete fields, and live validation.
Example of debouncing a search input:
import { useState, useEffect } from "react";
function Search() {
const [query, setQuery] = useState("");
const [debouncedQuery, setDebouncedQuery] = useState(query);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedQuery(query);
}, 500);
return () => clearTimeout(timer);
}, [query]);
useEffect(() => {
if (debouncedQuery) {
console.log("API call with:", debouncedQuery);
}
}, [debouncedQuery]);
return (
<input
type="text"
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}
In this example, the API call happens only after the user stops typing for 500 milliseconds.
Throttling Inputs
Throttling ensures that a function runs at most once within a specified time interval, regardless of how many times the event occurs. Throttling is useful for scroll events, window resizing, and button clicks that should not trigger too frequently.
Basic throttling example:
function throttle(fn, delay) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
}
};
}
Usage example:
const handleScroll = throttle(() => {
console.log("Scroll event handled");
}, 1000);
window.addEventListener("scroll", handleScroll);
This ensures the scroll handler runs only once every second.
Key Differences Between Debouncing and Throttling
Debouncing waits until user activity stops before executing a function, while throttling limits how often a function can execute during continuous activity. Debouncing is best for text inputs and search fields, whereas throttling is ideal for continuous events like scrolling or resizing.
Real-World Scenario
In a real-world application such as a search feature in a dashboard or resume builder, debouncing prevents sending an API request on every keystroke. Throttling is often used in analytics tracking, infinite scrolling, or resize handlers to maintain smooth performance.
Important Notes and Best Practices
Always clean up timers or event listeners to avoid memory leaks. Choose debouncing for input-based interactions and throttling for continuous events. Avoid hardcoded delays without considering user experience.
In summary, debouncing and throttling inputs help control event execution frequency, improve performance, and enhance user experience in React applications by preventing unnecessary re-renders and excessive function calls.