REACT

Synthetic Event


Synthetic events in React are standardized wrappers around the native browser events, ensuring consistency across different browsers. Since browsers can have varying names and implementations for events, React uses synthetic events to create a uniform interface. This allows developers to handle events in a consistent way, regardless of the browser being used.

React's synthetic events normalize event behaviour across different browsers, so you do not need to write browser-specific code. This ensures that your event handlers work consistently regardless of the user's browser.

 

Performance Optimizations

React uses the virtual DOM to optimize event handling. By leveraging event delegation and pooling, React can improve performance and reduce memory usage compared to directly using native events.

 

Additional Features

Synthetic events in React provide extra functionality to make event handling simpler and more powerful. They include useful methods like event.preventDefault() to prevent the default browser action and event.stopPropagation() to stop the event from propagating up the DOM tree.

 

Example:

// click event using synthetic events in a React component
import React from 'react';
function MyButton() {
 const handleClick = (event) => {
   event.preventDefault();
   console.log('Button clicked:', event);
 };
 return (
   <button onClick={handleClick}>
     Click Me
   </button>
 );
}
export default MyButton;


Explaination:

The handleClick function is invoked when the button is clicked. The event object passed to the function is a synthetic event.
 

Event Pooling and event.persist()

Because React pools synthetic events, the event object is reused and its properties are reset after the event handler has executed. If you need to use the event object asynchronously (e.g., inside a timeout), you should call event.persist():

const handleClick = (event) => {
 event.persist();
 setTimeout(() => {
   console.log('Button clicked:', event);
 }, 1000);
};


Event Handling in Class Components

In class components, handling events is similar, but you typically bind the event handler in the constructor:

 

Example:

import React, { Component } from 'react';
class MyButton extends Component {
 constructor(props) {
   super(props);
   this.handleClick = this.handleClick.bind(this);
 }
 handleClick(event) {
   event.preventDefault();
   console.log('Button clicked:', event);
 }
 render() {
   return (
     <button onClick={this.handleClick}>
       Click Me
     </button>
   );
 }
}
export default MyButton;