A Synthetic Event is an object that wraps the native browser event, following the W3C spec to ensure consistency. It behaves like the native event (has the same interface) but is managed internally by React.
When you write:
<button onClick={handleClick}>Click me</button>
The onClick
receives a SyntheticEvent, not the raw DOM MouseEvent
.
Why Use Synthetic Events?
React uses synthetic events for several reasons:
- Cross-browser compatibility
Different browsers implement DOM events slightly differently. Synthetic events normalize these differences, giving you a consistent API. - Performance via Event Delegation
React doesn’t attach listeners to every DOM node individually. Instead, it attaches a single event listener at the root and delegates events via the synthetic system. This makes it efficient, even in large apps. - Pooling and Reuse (in older versions)
React used to pool synthetic events for performance (i.e., reuse event objects). This meant that accessing the event object asynchronously (like in asetTimeout
) could lead to problems. Since React 17+, this behavior has been relaxed and pooling is effectively removed.
Common SyntheticEvent Properties
Synthetic events have most of the same properties and methods as native events:
event.type
→ Type of event (e.g."click"
)event.target
→ The target elementevent.currentTarget
→ The element the handler is bound toevent.preventDefault()
→ Prevents the default behaviorevent.stopPropagation()
→ Stops the event from bubbling up
Example: Using a Synthetic Event
function MyButton() { const handleClick = (event) => { console.log("Synthetic event type:", event.type); // "click" console.log("Target element:", event.target.tagName); // "BUTTON" event.preventDefault(); // Just an example, not needed here }; return <button onClick={handleClick}>Click Me</button>; }
In this example, event
is a SyntheticEvent, not the browser’s native MouseEvent
.
Types of Synthetic Events
React defines a range of synthetic events that match the types of DOM events, such as:
- Mouse Events:
onClick
,onDoubleClick
,onMouseEnter
- Keyboard Events:
onKeyDown
,onKeyPress
,onKeyUp
- Form Events:
onChange
,onSubmit
,onFocus
,onBlur
- Touch Events:
onTouchStart
,onTouchMove
- Clipboard Events:
onCopy
,onPaste
,onCut
- Drag Events:
onDragStart
,onDragOver
,onDrop
Each of these generates a corresponding SyntheticEvent subclass like SyntheticMouseEvent
, SyntheticKeyboardEvent
, etc.
Key Differences vs Native Events
Feature | Synthetic Event | Native DOM Event |
---|---|---|
Cross-browser support | Normalized and consistent | Varies between browsers |
Accessed in React | Yes (via props like onClick ) | Yes, but React wraps it |
Pooling | Was pooled (before React 17) | Not applicable |
Methods (e.g., preventDefault ) | Available and same as native | Same, browser-specific behavior may vary |
Source | Created and managed by React | Comes directly from the browser |