Open In App

How to Perform Debouncing in ReactJS ?

A Debouncing Events in ReactJS will allow you to call a function that ensures that a time-consuming task does not fire so often. It’s a function that takes a function as a parameter and wraps that function in a closure and returns it so this new function displays the “wait for a bit” behaviour.

Creating React Application And Installing Module:



Step 1: Create a React application using the following command:

npx create-react-app react-debouncing    

Step 2: After creating your project folder i.e. react-debouncing, move to it using the following command:



cd react-debouncing

 Step 3: After creating the ReactJS application, Install the required module using the following command:

npm install lodash

Project Structure: It will look like the following.

Project Directory

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.




import React, { Component } from "react";
import { debounce } from "lodash";
 
class WidgetText extends Component {
 
    state = { text: "" };
 
    handleChange = (e) => {
        this.setState({ text: e.target.value });
    };
 
    render() {
        return (
            <div>
                <input onChange={this.handleChange} />
                <textarea value={this.state.text} />
            </div>
        );
    }
}
 
class App extends Component {
 
    state = { show: true };
 
    handleToggle = debounce(() => {
        this.setState(prevState => ({ show: !prevState.show }));
    }, 500);
 
    render() {
        return (
            <div>
                <button onClick={this.handleToggle}>Toggle</button>
                {this.state.show ? <WidgetText /> : null}
            </div>
        );
    }
}
 
export default App;

Explanation:

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:


Article Tags :