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
import React from 'react'; export default function EventDemo() { const handleLinkClick = (e) => { // In React, returning 'false' does NOT work. // You must explicitly call preventDefault. e.preventDefault(); console.log("Link was clicked, but we didn't navigate!"); // 'e' is a SyntheticEvent. // If you ever desperately need the real browser event: console.log("Native Event details:", e.nativeEvent); }; const handleDivClick = (e) => { console.log("Div was clicked!"); }; const handleButtonClick = (e) => { // Stops the event from bubbling up to the div e.stopPropagation(); console.log("Button was clicked!"); }; return ( // Event bubbling still works perfectly with Synthetic Events <div onClick={handleDivClick} className="p-8 border-2 border-dashed border-gray-400"> <h3>Parent Div</h3> <p>Clicking the button will NOT trigger the Div's onClick, because of stopPropagation.</p> <button onClick={handleButtonClick} className="bg-blue-500 text-white p-2 rounded mr-4"> Click Me </button> <a href="https://google.com" onClick={handleLinkClick} className="text-blue-600 underline"> Fake Google Link </a> </div> ); }
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?