Open In App

Why we use synthetic events in React JS ?

Improve
Improve
Like Article
Like
Save
Share
Report

In React JS, there are events by which users interact the with an application UI. React listens to events at the document level, after receiving events from the browser, React wraps these events with a wrapper that has a similar interface as the local browser event, which helps us to use methods like preventDefault(). 

Prerequisites:

Why use such a wrapper?

We use different browsers where the same event has different names. Here wrapper does is triggering all the different names for the same event effect. Therefore, whenever we are triggering an event in a React JS, we are not trying to trigger the real DOM event, instead, we are using the React JS custom event type, which is the synthetic event.

Benefits of using synthetic events:

  • Cross browsers applications are easy to implement.
  • Synthetic events are that React JS reuses these events objects, by pooling them, which increase the performance.

Steps to create React Application And Installing Module:

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

npx create-react-app example

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

cd example

Project Structure:

Project structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example: Write down the following code in the App.js files.

Javascript




//App.js
import React from "react";
 
function App() {
 
    function handleClick() {
        alert("You clicked me!");
    }
 
    return (
        <div style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            height: "100vh"
 
        }}>
            <button onClick={() => { handleClick() }}>show alert </button>
        </div>
    );
}
 
export default App;


Step to Run the application: Run the application using the following command:

npm start

Output:


Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads