Open In App

How to Perform Debouncing in ReactJS ?

Last Updated : 02 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




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:

  • Have a simple page with a toggle button, if we click it the input fields go away and click it again to get the input field back and if we type in the input box the text will immediately mirror in the text area below.
  • We have a React WidgetText component, and it essentially just has the input and text area and then the app component itself has the toggle button.
  • Conditionally so if we click the toggle button it will come in into the handler grab, the previous state look at it shows bool off of the state and flip it, So if it was true then it will render the WidgetText if it is false we do not render the WidgetText.

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:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads