← Back to React, page 6

react-0118 · Medium mid

How does React's event system work, what changed in React 17 about event delegation, and how do native and React handlers interact?

React wraps native events in a SyntheticEvent that behaves the same in all browsers, and it uses event delegation: instead of attaching a listener to each element, it attaches one listener per event type to the root container. Before React 17 the listeners were on document. Since React 17 they are on the root container, which makes it safe to run several React versions on one page. A native listener on the target fires first, then React handlers, then listeners on elements above the root.

Full answer

When you write onClick={handleClick}, React does not call addEventListener on that button. At startup, createRoot(container) registers a listener for each supported event type on the root container. When an event bubbles up to the root, React finds the component whose element was the target, then runs the matching handlers of that component and its ancestors, in capture and bubble order, building the path from its own tree.

SyntheticEvent. The object passed to your handler wraps the native event with the same interface across browsers: target, currentTarget, preventDefault(), stopPropagation(), and the original event in event.nativeEvent. Since React 17 it is no longer pooled, so you can read it after an await. A few events behave differently from native ones: React's onChange for inputs fires on every keystroke (like native input), onFocus and onBlur bubble (like focusin and focusout), and onScroll does not bubble.

Event delegation. One listener per type on the root is cheaper than a listener per element, and it works for elements added later. React 16 attached them to document. That caused problems when multiple React versions or other libraries shared a page, because stopPropagation in one world affected another. React 17 moved listeners to the root container, so apps can be embedded in each other and migrate gradually.

Interaction with native listeners. The order for a click on a button inside the root is: native listeners on the button, then React's handlers (when the event reaches the root), then native listeners on ancestors above the root such as document or body. Calling event.stopPropagation() in a React handler also stops the native event at the root, so a document listener will not run. A native listener on document can no longer stop React handlers, because React already ran. Portals send React events through the React tree, not the DOM tree, so a click in a portal bubbles to React ancestors of the portal.

Practical rules: avoid mixing native and React listeners on the same elements; if you attach native listeners in effects, clean them up; prefer onClickCapture when you need capture order.

The example logs the order of native and React handlers.

jsx
import { createRoot } from 'react-dom/client';

const container = document.getElementById('root');
const log = (message) => console.log(message);

function App() {
  return (
    <div onClick={() => log('React: onClick on the div (parent)')}>
      <button onClick={() => log('React: onClick on the plain button')}>Plain</button>
      <button
        onClick={(event) => {
          log('React: onClick on the stopping button');
          event.stopPropagation();
        }}
      >
        Stopping
      </button>
    </div>
  );
}

createRoot(container).render(<App />);
await new Promise((resolve) => setTimeout(resolve, 30));

const [plain, stopping] = container.querySelectorAll('button');
plain.addEventListener('click', () => log('native: listener on the button'));
document.addEventListener('click', () => log('native: listener on document'));

log('--- click the plain button');
plain.click();
log('--- click the stopping button');
stopping.click();

This ran as a script in jsdom. The native listener on the button runs first, then the React handlers (the button, then its parent div), then the native listener on document. After stopPropagation in the React handler, the document listener does not run. Output of the run: --- click the plain button native: listener on the button React: onClick on the plain button React: onClick on the div (parent) native: listener on document --- click the stopping button React: onClick on the stopping button

Key points

  • React delegates events: one listener per event type on the root container.
  • React 17 moved listeners from document to the root container, allowing several React versions on one page.
  • SyntheticEvent wraps the native event, is no longer pooled, and exposes nativeEvent.
  • Order: native on the target, then React handlers, then native listeners above the root.
  • stopPropagation in a React handler also stops listeners above the root, such as document.

Common mistakes

  • Expecting a document listener to run before React handlers.
  • Using stopPropagation in React and wondering why document-level listeners stop firing.
  • Reading the event object after an await in React 16 code, where events were pooled.
  • Adding native listeners in effects without cleaning them up.
  • Assuming onScroll bubbles.

Follow-ups

  • Why did React 17 move listeners from document to the root container?
  • How do React events behave through a portal?
  • What does the capture variant of an event handler (onClickCapture) change?

Tips

  • Describe the root-container delegation and the version 17 reason.
  • Give the order: native target, React, native ancestors.
  • Mention portals send events through the React tree.