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” behavior.
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:
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.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
- 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:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: