Debouncing vs Throttling in React
Both debouncing and throttling are techniques to control the rate at which a function is executed, often used to improve performance when dealing with events like resizing, scrolling, or typing. Here's a simple explanation:
Definition: Executes a function after a specified delay from the last time it was invoked. If the event keeps firing, the timer resets.
Use Case: When you want the function to run only once after the user stops triggering the event.
Example: API call after the user stops typing in a search box.
Code Example (Debouncing in React)
import React, { useState } from "react";
function debounce(func, delay) {
let timer;
return (...args) => {
clearTimeout(timer); // Clear the previous timer
timer = setTimeout(() => func(...args), delay); // Set a new timer
};
}
const App = () => {
const [value, setValue] = useState("");
const handleChange = debounce((e) => {
console.log("API Call for:", e.target.value);
}, 1000);
return (
type="text"
onChange={(e) => {
setValue(e.target.value);
handleChange(e);
}}
value={value}
placeholder="Type something..."
/>
);
};
export default App;
Behavior: The function (handleChange) executes only after the user stops typing for 1 second.
Definition: Executes a function at most once in a specified time interval, even if the event keeps firing.
Use Case: When you want the function to run at a consistent interval during frequent events.
Example: Logging the position of the page while scrolling.
Code Example (Throttling in React)
import React, { useEffect } from "react";
function throttle(func, limit) {
let lastFunc;
let lastTime;
return (...args) => {
const now = Date.now();
if (!lastTime || now - lastTime >= limit) {
func(...args);
lastTime = now;
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if (Date.now() - lastTime >= limit) {
func(...args);
lastTime = Date.now();
}
}, limit - (now - lastTime));
}
};
}
const App = () => {
const handleScroll = throttle(() => {
console.log("Scroll event logged:", window.scrollY);
}, 1000);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return
Scroll down the page;export default App;
Behavior: The handleScroll function logs the scroll position at most once every second, even if the scroll event fires continuously.
The above is the detailed content of Debouncing vs Throttling in React. For more information, please follow other related articles on the PHP Chinese website!