Debouncing in React.JS

Sankhadip Samanta
The Startup
Published in
2 min readSep 14, 2020

--

From https://dev.to/

Debouncing in Javascript is an exercise to enhance browser performance during any time-consuming computations. If such a method is invoked frequently then it may degrade our web app performance. Debouncing is a programming practice used to ensure that a time-consuming task does not fire so often. In other words, it limits rates at which functions get invoked.

Application

  • Debouncing can be implemented where searching works like when the user will be typing in the search box and the search results will come from the server. There we can hit server API after the user stops typing(after a certain delay). Here if on every change there is frequent server API hit then it will degrade our server performance very much.
  • Another application of debouncing is in content-loading webpages like Facebook and Twitter where the user keeps on scrolling. In these scenarios, if the scroll event is fired too frequently, there might be a performance impact, as it contains lots of videos and images. Thus the scroll event must make use of debouncing.

Implementation

Let’s go ahead and create a React Project.

Open the App.js file and replace the following code

Explanation

  • debounce function which will do the actual work of delaying invoking function.
  • OnChange of the input field, we get event and pass it to the update function as an argument.
  • Update calls debounce function with passing 2 arguments (a function and seconds)
  • We do e.persist() in OnChange because when we will try to access an event inside callback, event’s reference will be nullified and we get undefined. If you try out the above code without e.persist(), then you will realize what particular error appears in the console.

For more information on e.persist(), please visit

https://reactjs.org/docs/events.html

  • The general idea for debouncing is:
    1. Start with 0 timeout
    2. If the debounced function is called again, reset the timer to the specified delay
    3. In case of timeout, call the debounced function
    Thus every call to a debounce function resets the timer and delays the call.

Here in the above code, after every 1 sec of typing pause, callback function will get executed and will set the value to state, and in between 1 sec if the user types again the timer will be reset again to 0.

Few points are taken from GeeksForGeeks.

Check out GitHub repository for source code.

Sankhadip Samanta

Full Stack Developer, Code Quotient | Tech Writer and Social Media Handler at BlogMarch

Find me on Linkedin 😃 and Github 😅

--

--