DEV Community

Anjali Gurjar
Anjali Gurjar

Posted on

What is Event and syncthetic event in React

In React, the terms Synthetic Event and Event are often used interchangeably, but they refer to slightly different concepts within the React ecosystem. Here's a detailed explanation of both:

  1. Event in React (Native Event) The native event refers to the event object that is used in the standard JavaScript DOM event system. It is the same event object you would work with when using vanilla JavaScript, such as when you add event listeners to DOM elements using methods like addEventListener. The native event object contains information about the event, such as which element triggered it, the type of the event, and various properties and methods (e.g., preventDefault, stopPropagation, etc.).

Synthetic Event in React
In React, Synthetic Events are React's custom, normalized event system that wraps around the browser's native events. React uses synthetic events to ensure that events behave consistently across different browsers, making it easier for developers to write cross-browser compatible code without worrying about inconsistencies in event behavior.

The SyntheticEvent is an abstraction provided by React to handle events in a more efficient and unified way. Synthetic events provide a normalized API that works the same in all browsers, regardless of their native implementation. React’s synthetic event system uses event delegation by attaching a single event listener to the root of the DOM (on the document object) and then managing all other events through that listener, which helps with performance.

Key Differences Between Native and Synthetic Events in React

  1. Normalization Across Browsers: Native Events: These events are dependent on the browser's implementation, which means behavior can vary slightly across browsers. Synthetic Events: React normalizes these events to provide a consistent API across all browsers, making event handling predictable.
  2. Event Pooling: Native Events: Native events are separate instances and don’t have pooling. Once the event handler is done executing, the event object can be accessed freely. Synthetic Events: React uses event pooling. After the event handler is executed, the event object is reused and reset to free up memory. This means you can’t access the event object asynchronously unless you call event.persist() to remove it from the pool.
  3. Event Delegation: Native Events: In the native event system, you attach event listeners directly to the target DOM elements. Synthetic Events: React uses event delegation, meaning all event listeners are attached at the root of the DOM tree, and React handles dispatching the event to the correct target element. This is more efficient, especially in large applications.
  4. API Differences: Native Events: The properties and methods available on the native event object can vary from browser to browser. Synthetic Events: React ensures that the SyntheticEvent object provides a consistent API across all browsers. For example, React provides properties like event.target, event.preventDefault(), event.stopPropagation(), and others in a uniform way. Example of Synthetic Event in React: jsx Copy code import React from 'react';

function MyComponent() {
const handleClick = (event) => {
console.log(event); // This is a Synthetic Event object in React
console.log('Event type:', event.type);
event.preventDefault(); // You can still use preventDefault and other methods
};

return Click me;
}

export default MyComponent;
In this case, event is a SyntheticEvent object that React provides. It has the same properties and methods as a native event object, but React ensures that it's normalized and consistent across browsers.

Event Pooling Example:
When using synthetic events in React, the event object is pooled, which means it will be reset and reused after the event handler finishes executing. This can lead to problems if you try to access the event object asynchronously (e.g., inside a setTimeout or Promise).

jsx
Copy code
import React from 'react';

function MyComponent() {
const handleClick = (event) => {
console.log(event); // Access the event object

// React will nullify the event object after the handler executes, causing issues if accessed asynchronously.
setTimeout(() => {
  console.log(event);  // React nullifies the event object unless persist() is called
}, 1000);

// To prevent event pooling, use event.persist()
event.persist();
Enter fullscreen mode Exit fullscreen mode

};

return Click me;
}

export default MyComponent;
In this case, event.persist() is called to prevent React from nullifying the event object, which allows you to use it asynchronously in the setTimeout function.

Summary:
Native Events: The raw event object provided by the browser's event system.
Synthetic Events: React's normalized event system that wraps the native events, ensuring consistent behavior across all browsers.
React uses synthetic events for better cross-browser compatibility and performance optimization. When using React, you typically work with SyntheticEvent, and it's important to remember that these events are pooled unless you call event.persist() to preserve them for asynchronous use.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more