Synthetic Events
Definition
A Synthetic Event is a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event (like `preventDefault()` and `stopPropagation()`), but works identically across all browsers.
Explain Like I'm New
Imagine every browser (Chrome, Safari, Firefox) speaks a slightly different language when a user clicks a button. In the old days, developers had to write code to translate all three languages (e.g., using jQuery). React solves this with the 'Synthetic Event'. When you click a button, React intercepts the browser's native click, translates it into its own universal 'React Language' (the Synthetic Event), and hands THAT to your `onClick` function. Now you don't have to worry about browser differences.
Real World Example
If you write `<button onClick={handleClick}>`, the `e` in `handleClick(e)` is NOT the standard DOM `MouseEvent`. It is a React `SyntheticEvent`. If you look inside it, you'll see a property called `e.nativeEvent` which holds the original, messy browser event.
Common Use Cases
- •Providing a consistent Event API across all browsers (IE, Chrome, Safari)
- •Optimizing performance through 'Event Pooling' (in React 16 and older)
- •Delegating all events to the root of the document for performance
Interactive Example
Interview Questions
basic
- What is a Synthetic Event?
- How do you stop a form from refreshing the page in React?
intermediate
- How does React actually attach event listeners to the DOM?
- What is 'Event Delegation' in React?
advanced
- What was 'Event Pooling' in React 16, and why was it removed in React 17?
- If you need to access the raw, underlying browser event, how do you do it?
trick
- Can you return `false` from an `onClick` handler to prevent default behavior in React?