Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
debounce with react hooks JavaScript

Avoid multiple clicks using debounce with react hooks

  • February 16, 2021June 20, 2021
  • by Coder Kai

Why debounce with react hooks? We all come across that one button users keep on pressing until the data is loaded. Without guarding your code with every sort of if conditions, you can guard this by debouncing. For multiple tap scenarios, you can either propagate the event at the first tap/click or the last one.

Debouncing with hooks can be a bit tricky to sort out. The problem is the functional components in react will initialize the function when rendering. To avoid that and register a debouncing function you can use the following method.

How to use debounce with react hooks

We will be using the lodash debounce function https://lodash.com/docs/4.17.4 to debounce and avoid multiple tap action. In this simple example, a tap on the button will be used to explain how to use the debounce function.

Here we use useCallback hook to avoid updating the debounce function when re-rendering the component on state change. This is very important in these kind of implementations to avoid initializing functions every time when renders or state changes.
Note that we have passed clicks as a parameter to avoid the debounce function using the initial values in the function callback. For these kinds of state updates, you may need to use a closure that can be updated from parameters provided to the debounce function.

const {useState, useCallback } = React;
const  INTERVAL = 1000;

const Button = ({label, onClick}) => {
  return (
    <div className="button" onClick={onClick}>{label}</div>
  );
}

const App = () =>  { 
  const [clicks, setClicks] = useState(0);

  // Add once click to the existing state value
  const clickOnce = (click) => {
    setClicks(click + 1);
  }
  
  // debounce the click function
  // note that the clicks are passed as a parameter to avoid repeating the initial value
  const debouncedClick = useCallback(_.debounce((clicks) => {
    clickOnce(clicks);
  }, INTERVAL, {leading: true, trailing: false, maxWait: INTERVAL}), []);
  
 
  return (
    <div>
      <Button label="Click Button" clicks={clicks} onClick={() => debouncedClick(clicks)}/>
      <div className="click-count">Click Count: {clicks}</div>
    </div>
  );
};


ReactDOM.render(
  <App />,
  document.getElementById('app')
);

Above is the codepen example. Here we have used an extra button component to increase the count. When you tapping the button, you will notice that the count is increased every second which is the INTERVAL const declared at the beginning of the js script. Also, you can use different kinds of options to suit your needs. The maxWait and interval are two important parameters you would need to understand better as well.

See the Pen Debounce using React hooks by Sandaruwan Nanayakkara (@sandaruny) on CodePen.

Also if you need to use debounce on react component class checkout following link:

Debounce and avoid multiple clicks event generation on React.js components using Lodash
How to avoid NullPointerException in Java
How to optimize react-native map views
Coder Kai
A humble developer

Related articles

Multiple refs for an array of React Elements
Using multiple refs for an…
Immutable and Mutable Values in Javascript
07. Immutable and Mutable Values…
wrapper objects in javascript
06. Wrapper objects in Javascript
globals undefined and null values in javascript
05 Global, null and undefined…
Javascript Booleans and Equality
04. Javascript Guide Booleans and…
How to add Chakra UI Animations
Chakra UI Animations
SSL Websocket using Nginx Proxy
SSL Websocket proxy with Nginx…
Change python version correctly
Python is not setting correct…
optimize React.js load time
How to optimize React.js app…
Multiple refs for an array of React Elements
How to use IntersectionObserver to…
Multiple refs for an array of React Elements
How to dismiss dropdowns when…
Javascript guide Strings
03. Javascript Guide – Strings
How to fetch data with useEffect
How to fetch data with…
add styles to stripe elements
How to add styles to…
Typescript
How to use Typescript with…
how to optimize react-native map view
How to optimize react-native map…
react-native heap limit allocation
Android/iOS React-native heap limit allocation…
androidx fileprovider
AndroidX ClassNotFound Exception: “android.support. v4.content…
Numbers inJavascript
02. Javascript Guide – Numbers
Introduction to Javascript
01. Javascript Guide – Introduction…

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • sign up for binance on 07. Immutable and Mutable Values in Javascript
  • Dang k'y d nhn 100 USDT on Using multiple refs for an array of React Elements
  • b^onus de inscric~ao na binance on How to optimize React.js app load time using react lazy

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress