Introduction
In this article, we will look at the debouncing, programming technique that controls how often functions are called to improve performance. It can prevent time-consuming tasks from triggering too frequently, which can slow down web pages or another performance issue.
Debouncing
In React.js, debouncing is commonly used to improve performance by limiting the rate at which a function, such as an event handler, is called. This is particularly useful for optimizing search input fields, scroll events, and window resizing, where frequent updates can degrade performance.
Debouncing and throttling are both useful to stop unnecessary load to the backend side so and debouncing is on front end side and throttling works at the back-end side Let's look a little bit into throttling is a process that also prevents multiple requests from the user side at the same time but it ensures that function will execute regularly at least once in a given time period. So debouncing is used at the front-end side to manage multiple requests triggering at the same time to the back-end side.
Here we have an example of debouncing.
Suppose that there is one page and on that page, there is a search functionality that sends requests at the backend side on every render or every keypress when we type something to get results from the backend side. but what happens that normally uses types 5-7 characters in 5 seconds now when the user types onChange event will call and it will request 5-7 times to the back-end side in 5 seconds it means it leads to slow performance because suppose that we type 100+ keywords means the event will send 100+ requests at backend side to fetch result according to the input value. That is not what we want. so to fix this issue we use debouncing.
Example
const Input = () => {
const onChange = (e) => {
// Logic for search result from database.
};
return <input onChange={onChange} />;
};
Here in the above example, we have not used debouncing so it will lead to performance issues due to the frequent triggering of events. here if I type the “experience” keyword it means it will send a request to the data database to fetch results according to matches like “e”, “ex”,”exp”, ..so on in such a way it will send request to database according to keyword length.
Here is an example of debouncing.
const Input = () => {
const onChange = (e) => {
// Logic for search result from database
};
const debouncedOnChange = debounce(onChange, 500);
return <input onChange={debouncedOnChange} />;
};
In the above example, we have implemented debouncing now what happens when the user types something it will wait until we stop typing from the initial time to the given time period and then it will trigger the event and execute a task.
In such a way we can use debouncing to prevent some execution that leads to slow performance.