A Synthetic Event in React is a wrapper around the native DOM event that provides a consistent and cross-browser interface for handling events in React applications.
Why Synthetic Events?
- Different browsers handle events differently, which can cause inconsistencies.
- React’s SyntheticEvent normalizes event behavior across browsers, ensuring that event properties work the same everywhere.
Key Points About Synthetic Events:
Feature | Description |
---|---|
Cross-Browser Compatibility | Handles browser inconsistencies automatically. |
Pooling | Reuses event objects for performance optimization. |
Event Properties | Access event properties like target , type , currentTarget . |
Stop Propagation & Prevent Default | Supports e.stopPropagation() and e.preventDefault() like native events. |
Example:
javascriptCopyEditfunction ButtonClick() {
const handleClick = (e) => {
console.log(e.type); // Synthetic Event
console.log(e.target); // Element that triggered the event
e.preventDefault();
};
return <button onClick={handleClick}>Click Me</button>;
}
e
is a SyntheticEvent object.- Properties like
e.type
,e.target
,e.preventDefault()
work similarly to native events.
Synthetic Event Pooling:
React pools SyntheticEvent objects to improve performance.
- Events are re-used after the event callback is executed.
- Accessing event properties asynchronously can lead to issues.
Example:
javascriptCopyEditfunction App() {
const handleClick = (e) => {
console.log(e.type); // Works fine
setTimeout(() => {
console.log(e.type); // May not work due to pooling
}, 1000);
};
return <button onClick={handleClick}>Click Me</button>;
}
Solution – Use e.persist()
:
javascriptCopyEditconst handleClick = (e) => {
e.persist(); // Prevents the event from being reused
setTimeout(() => {
console.log(e.type); // Now works as expected
}, 1000);
};
Benefits of Synthetic Events:
Abstracts browser differences – consistent behavior across browsers.
Performance optimized – Event pooling reduces memory usage.
Consistent API – Unified event properties like
target
, type
.
Summary:
Synthetic Event is React’s abstraction over native DOM events.
It normalizes event handling across browsers and improves performance through event pooling.
Use e.persist()
if accessing event data asynchronously.