Synthetic Event In React
Introduction
An event is a triggered action that occurs due to a user action or a system-generated event. Pressing a key, mouse click, a web page loading, window resizing, and other interactions are examples of events.
We wouldn't be able to construct awesome responsive web applications that respond to a user's every touch without event handlers in React or any other framework for that matter.
Event handling is essential because it ensures that React keeps track of each action taken by the user. React has its event handling system that works similarly to how DOM elements handle events.
In this article, we’ll be discussing synthetic events in React. So, let’s get started!
Also See, Dropdown in React JS
Synthetic Events
React uses a synthetic events system to ensure that React apps and interfaces are consistent and fast. It provides consistency by normalizing events across browsers and systems so that they have the same properties.
With the help of an example, we are aware of the onclick event that occurs when the user clicks on an element. So, that onClick event does not exist in a Windows or Android app.
That code will not work if we use a native onClick event. When we compile our React code, it can replace reactOnClick with native click events for any platform. Provided we abstract it behind another function like reactOnClick.
Synthetic events have allowed react to run in Electron for mobile apps and react native for iOS and Android.
Furthermore, because a single native event can generate multiple synthetic events, it allows you to create new ones quickly.
For example, a syntheticTap event could be emitted if you receive a native touchStart then a native touchEnd in succession.
function Form() {
function handleSubmit(e) {
e.preventdefault();
console.log("Hey, you hit submit");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Here, e is a synthetic event. React defines these synthetic events according to the W3C spec so, we don't have to worry about cross-browser compatibility.
One important point to note here is that:
- The synthetic events are distinct from the browser's native events and do not map directly to them. Abstraction is the term for this type of pattern. We can inject multiple implementations based on what we're writing by separating the code we write from how it runs.
For example, OnMouseLeave event.nativeEvent, will point to a mouseout event. The mapping is not part of the public API and is subject to change at any time.
The attributes of a synthetic event object are as follows:
- boolean bubbles
- boolean cancelable
- boolean defaultPrevented
- boolean isDefaultPrevented()
- boolean isTrusted
- boolean isPropagationStopped()
- DOMEventTarget target
- DOMEventTarget currentTarget
- DOMEvent nativeEvent
- number eventPhase
- number timeStamp
- string type
- void preventDefault()
- void stopPropagation()
- void persist()
Synthetic Event Pooling
Synthetic event objects are pooled. React nullifies all properties on the object the event handler has been called for performance reasons, preparing the Synthetic event instance passed to your event handler for reuse.
This means that you won't get the expected results if you try to use the event asynchronously. This, for example, will not work:
function handleChange(e) {
setTimeout(() => {
console.log(e.target.value);
}, 100);
}
If you need to access the properties of an event object after the event handler has finished, use e.persist():
function handleChange(e) {
// It avoids react from resetting its properties
e.persist();
setTimeout(() => {
console.log(e.target.value); //It will work!
}, 100);
}
Advantages of Synthetic Events
- They are simpler to use because they require far less code.
- It is supported without any hassle among the browsers.
- They're more reliable because React adds them after the element has been rendered and is in the DOM.
You can visit the official react documentation to learn more about synthetic events in React.
Frequently Asked Questions
Q1) Why do we need synthetic events in React?
Ans: React uses a synthetic event system to ensure that React apps and interfaces are consistent and fast. It achieves consistency by normalizing events across browsers and platforms so that they have the same properties.
Q2) What is event pooling?
Ans: Event data is sent to the callback when an event fires, known as event pooling. The object is then cleaned up for later use. It means that we can't save event data in the state and then access it asynchronously, run a timeout, and reassess the event.
Q3) What are native events in react?
Ans: Events are received by React Native via the bridge that connects native code and React. In other words, whenever a View is created, React sends its ID number to native, allowing it to receive all events related to that element.
Key Takeaways
In this article, we've learned about synthetic events in react, pooling in synthetic events, and their benefits.
Check out this problem - Smallest Distinct Window .
If you want to learn advanced front-end web development, Coding Ninjas has one of the best courses available, which you can find here.
Thank you for reading!