Debouncing in React
Anubhav Raina
SDE at Edelman Financial Engines | Frontend Development | React | Redux | Javascript ES6 | CSS3 | HTML5 | GIT | Responsive Web Design
Today I made this small project as a task for a job application. Here I learnt the concept of debouncing. It was new to me, can be for many. So thought of sharing. Hope it helps. You can share more in comments.
When to Use Debouncing?
Let's understand this with an example. Suppose we have an input element that gets some data when we type something. For example, let's say we type any book-name, and it returns some data.
But there is a catch here. Let's say our book-name is Atomic Habits. If we type the first character, that is A, we will send request to the backend server. Then we type t, and we will send another request to the server, and so on. ?
This calls the API so many times, and in turn overuses the requests. So, to prevent this, we use something called a debounce function.
So to achieve this, we have a feature in JavaScript called Debouncing.
领英推荐
In the case of Debouncing, the API will trigger only once after 2 seconds, after we type our whole book-name.
In this useEffect Hook, we will have a function called debounceFetch. This function will have a callback function called setTimeOut. And we will set the timer for 2 seconds.
We will also need to destroy the instance of the useEffect hook using return, followed by clearTimeout, every time it finishes.
Now, if we type any search query in the input, it will display after 2 seconds just when we stop changing the input. And we used debouncing to do this.
There are multiple applications of debouncing. We can use it to keep from hitting our API over and over. And we can use it to make sure the the form data gets submitted only once, even if we click the submit button multiple times
Student at Thapar University
9 个月Keep going champ