Debouncing is a programming technique used to limit the rate at which a function executes. It is particularly useful when dealing with events that fire frequently, such as keystrokes, API calls etc.
Why Debouncing?
For example, when users type in a search box, the input event is triggered every time a key is pressed. Without debouncing, an API call would be made on every keystroke, causing unnecessary network requests. Debouncing ensures that the function (e.g., API call) executes only after the user has stopped typing for a certain period.
Implementing Debouncing
1. Setting up state
const [fieldValue, setFieldValue] = useState("");
2. API Call Function
const getData = () => {
console.log("----API Call----");
};
This function simulates an API call by logging "----API Call----"
to the console.
3. Implementing Debouncing using useEffect
useEffect(() => {
const apiCallTimeout = setTimeout(() => {
getData();
}, 2000);
return () => clearTimeout(apiCallTimeout);
}, [fieldValue]);
- Whenever
fieldValue
changes, the effect runs. - A
setTimeout
is set for 2000 milliseconds (2 seconds) to callgetData()
. - If the user continues typing before the 2-second delay, the previous
setTimeout
is cleared, and a new one starts. - The cleanup function (
return () => clearTimeout(apiCallTimeout);
) ensures that only the last keystroke (after the user stops typing) triggers the API call.
4. Without Debouncing
// useEffect(() => {
// getData();
// }, [fieldValue]);
- If this version is used,
getData()
would run every timefieldValue
changes, causing multiple API calls for every keystroke. - This leads to unnecessary network requests and potential performance issues.
5. Input Field
return (
<div className="App">
<input
type="text"
onChange={(e) => setFieldValue(e.target.value)}
value={fieldValue}
placeholder="Search"
/>
</div>
);
Full Code
import { useEffect, useState } from "react";
function DebouncingExample() {
const [fieldValue, setFieldValue] = useState("");
const getData = () => {
console.log("----API Call----");
};
// ------------------Debouncing--------------------
useEffect(() => {
const apiCallTimeout = setTimeout(() => {
getData();
}, 2000);
return () => clearTimeout(apiCallTimeout);
}, [fieldValue]);
// ----------------Without debouncing------------------
// useEffect(() => {
// getData();
// }, [fieldValue]);
return (
<div className="App">
<input
type="text"
onChange={(e) => setFieldValue(e.target.value)}
value={fieldValue}
placeholder="Search"
/>
</div>
);
}
export default DebouncingExample;
Debouncing is an essential technique to improve performance and avoid excessive function executions. In this case, it helps prevent multiple API calls on every keystroke by delaying execution until the user pauses typing.
It is widely used in search boxes, form validations, and resize events to improve efficiency and user experience.
Top comments (0)