Synthetic Events in React are cross-browser wrapper objects around the native browser events.
- React creates them to normalize differences between browsers, ensuring events behave the same everywhere.
- They are pooled for performance (reused internally), so accessing them asynchronously requires special handling.
Key Points
- Cross-browser compatibility
- Handles differences like
event.targetvsevent.srcElement.
- Handles differences like
- Same interface as native events
- Methods like
preventDefault()andstopPropagation()work as usual.
- Methods like
- Event pooling
- Event objects are reused to improve performance.
- To access them asynchronously, use
event.persist().
Example
import React from "react";
function App() {
const handleClick = (event) => {
event.preventDefault(); // prevent default behavior
console.log(event.type); // "click"
// To use the event asynchronously
const e = event;
setTimeout(() => {
console.log(e.type); // Might not work without event.persist()
}, 1000);
// Use persist() to retain event
event.persist();
setTimeout(() => {
console.log(event.type); // Works after 1 second
}, 1000);
};
return (
<button onClick={handleClick}>Click Me</button>
);
}
export default App;
💡 In Short:
React's Synthetic Events wrap native browser events to provide a consistent, cross-browser API with improved performance. Use
event.persist()if you need to access the event asynchronously.