Table of contents
No headings in the article.
In this article, we are gonna see in detail what the heck is Debouncing in JS.
Prerequisite => Basic level of understanding of JavaScript and React will be a plus point.
What is Debouncing -> Debouncing is a concept that makes sure that our code is only triggered once per user input to avoid unnecessary CPU cycles, and API calls and to improve performance.
For this I am having several examples, when you are pressing a key on the keyboard, the signal travels so quickly that before we manage to release the key it bounces and it could trigger several click events. To prevent this, the keyboard stops processing events for a few microseconds after pressing a key on the keyboard. This pattern is called Debouncing.
Don't worry if you did not understand this, I will try to make you understand with a different analogy.
We all have used some e-commerce apps ( amazon or Flipkart), there we can notice that when we are typing in the search bar after completing the typing only the event got triggered and we get the search result. (If you didn't notice it before then try it)
I have implemented debouncing in two ways, the first one is in vanilla JS and the other one is in React.
Debounce in vanilla JS => Before starting we have to think about how we can make wait for our code for a certain amount of time. Guess?? Yeah, you are right. We will use setTimeOut function.
Now we have to hold that timeout function while the user is typing. So we have to save the id of the timeout and we have to clear those timeouts while the user is busy typing. Let's see our code.
import "./styles.css";
let timerId;
let counter = 0;
const debounceInput = document.getElementById("debounce-input");
const debouncer = (e, timeout) => {
clearTimeout(timerId);
timerId = setTimeout(() => {
printData(e);
}, timeout);
};
const printData = (e) => {
counter++;
console.log(e.target.value, "counter", counter);
};
debounceInput.addEventListener("keydown", (e) => debouncer(e, 1000));
So hereafter every keydown the setTimeOut method will be called and that will be cleared if the user presses any button on the keyboard again.
So we have to save the previous setTimeout id for clearing the timeOut in the current event if the event occurred in between 1 second. So I save the timerId as a global variable. You can also write a wrapper function for this.
Let's see the output=>
Debouncing in React
Here I have implemented a small ecom search functionalities in React.
Let's see the code first ->
import { useEffect, useRef, useState } from "react";
import { getBrands } from "./data";
import "./styles.css";
export default function App() {
const [data, setData] = useState(getBrands());
let timerId = useRef();
let [input, setInput] = useState("");
useEffect(() => {
clearTimeout(timerId.current);
timerId.current = setTimeout(() => {
setData(
getBrands().filter((el) => el.name.includes(input.toLowerCase()))
);
}, 300);
}, [input]);
return (
<div className="App">
<div>
<input value={input} onChange={(e) => setInput(e.target.value)} />
</div>
<ul>
{data.map((el) => {
return <li>{el.name}</li>;
})}
</ul>
</div>
);
}
Instead of global variable I saved the timerId as a useRef variable. So after 300 milliseconds it will check whether we are typing or not and when some input changes we are triggering the useEffect function. Other things are same as before.
Both codesandbox link=>
codesandbox.io/s/debouncing-in-js-17jvyv?fi..
codesandbox.io/s/debouncing-in-react-ypelcp
Thank you very much for reading this blog. Please feel free to comment here. I like to get your feedback.