Sub topic 14
How React Delegates Events
This chapter assumes you know how to attach handlers with props such as onClick, how bubbling and stopPropagation work in the DOM, and how to use useEffect for native listeners. It explains what React does between the browser's click and your handler running. This explains behavior that otherwise looks odd: handlers that fire in a surprising order, stopPropagation that doesn't stop a native listener, and events that bubble through portals.
What delegation means
When you write <button onClick={handleClick}>, React does not call addEventListener on that button. It keeps a record of the handler in its own tree of components and elements.
React registers one listener per event type on the root container, the DOM node you pass to createRoot. When a click happens, the browser bubbles the native event up to that root. React's listener then does the following:
- Reads
event.targetto find the DOM node that was clicked. - Finds the React element for that node and walks up through its parents.
- Collects every
onClickhandler along the way, and everyonClickCapturehandler for the capture phase. - Calls them in order, wrapped in a React synthetic event object.
This pattern is called event delegation. A page with 10,000 list items needs no more listeners than a page with one, and elements added or removed later need no registration work.
The synthetic event
The e in onClick={e => ...} is a SyntheticEvent. It wraps the native event and gives the same interface across browsers: target, currentTarget, preventDefault(), stopPropagation(), and the type-specific fields such as key and clientX.
Three details matter in practice:
e.nativeEventgives you the underlying browser event when you need something React doesn't expose.e.currentTargetis the DOM node of the element whose handler is running.e.targetis the node where the event started, which may be a descendant.- Since React 17 there is no event pooling. In React 16 the event object was reused and its fields were cleared after the handler returned, so reading
e.targetin asetTimeoutgavenull. You can now read the event asynchronously, though copying the value you need is still clearer.
Root container, not document
Before React 17, React attached its listeners to document. From React 17 on, it attaches them to the root container. This change exists so that several React versions, or React next to other libraries, can coexist on a page without their listeners interfering.
| Aspect | React 16 | React 17 and later |
|---|---|---|
| Listener location | `document` | Root container node |
| Event pooling | Yes | No |
| `onScroll` bubbling | Bubbles | Does not bubble |
| `onFocus` / `onBlur` | Mapped to native `focus` / `blur` | Mapped to native `focusin` / `focusout` |
| `stopPropagation` blocks `document` listeners | No | Yes |
The last row has the most practical effect, as the next section shows.
Ordering against native listeners
Native listeners attached directly to a DOM node run before React handlers for that event. The native event must bubble up to the root container before React sees it, so anything on the way fires first. Listeners on document run after React, because document is above the root.
import { useEffect, useRef } from 'react';
export function OrderDemo() {
const buttonRef = useRef(null);
useEffect(() => {
const button = buttonRef.current;
const onButton = () => console.log('1. native listener on the button');
const onDocument = () => console.log('3. native listener on document');
button.addEventListener('click', onButton);
document.addEventListener('click', onDocument);
return () => {
button.removeEventListener('click', onButton);
document.removeEventListener('click', onDocument);
};
}, []);
return (
<button ref={buttonRef} onClick={() => console.log('2. React onClick')}>
Click me
</button>
);
}Clicking logs 1, 2, 3 in order. Now change the React handler to call e.stopPropagation():
<button
ref={buttonRef}
onClick={e => {
console.log('2. React onClick');
e.stopPropagation();
}}
>
Click me
</button>In React 17 and later, line 3 no longer appears. React's stopPropagation calls the native method on the event while it sits at the root container, so the event never reaches document. In React 16 it did reach document, because React was already on document and stopPropagation does not block other listeners on the same node.
The reverse case catches people out. If a native listener on the button or any element below the root calls stopPropagation(), the event never reaches the root, and no React handler runs for it.
Capture and bubble phases
React registers both a capture and a bubble listener at the root for each event type. When it dispatches, it simulates both phases over its own tree. For a click on a button inside a div, the order is:
onClickCaptureon thedivonClickCaptureon the buttononClickon the buttononClickon thediv
The native browser phases have already happened by then. React's root capture listener runs first in the native capture phase, then the native event travels down to the target and back up to the root bubble listener. Between those two moments, native capture and target listeners on the DOM elements run. In practice this means native listeners below the root still run before React's bubble handlers.
Events that behave differently
Not every event follows the plain "bubble to root" path.
- Focus. The native
focusandblurevents do not bubble. React mapsonFocusandonBlurtofocusinandfocusout, which do bubble. That is why a handler on a<form>or<div>can detect focus entering any of its inputs. - Scroll.
onScrolldoes not bubble in React 17 and later. A handler on a parent does not fire when a child scrolls. Attach it to the scrolling element itself. - Wheel and touch. React registers
onWheel,onTouchStart, andonTouchMoveas passive listeners, as browsers recommend for scrolling performance. Callinge.preventDefault()in them has no effect and logs a console warning. If you need to block scrolling, attach a native listener with{ passive: false }in an effect. - Non-delegable events. Some events, such as
loadon images orplayon media elements, do not bubble at all. React attaches those listeners directly to the element.
Portals follow the React tree
Delegation maps the DOM target back to React elements, and then bubbles through the React tree rather than the DOM tree. This shows with portals. A portal renders children into a different DOM node, but the events still travel to the portal's React parents.
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal">{children}</div>,
document.body
);
}
export function Page() {
return (
<div onClick={() => console.log('Page div received the click')}>
<Modal>
<button>Inside the modal</button>
</Modal>
</div>
);
}The modal's DOM node is a child of document.body, not of the page div. A click on the button still logs the message, because in the React tree the Modal is a child of the div. This is usually what you want, since a portal modal can report events to the component that opened it. It also means a "click outside" check that relies on e.target being a DOM descendant needs care. Use contains on a ref, or call stopPropagation in the portal.
Debugging tips
- If a handler never fires, check whether a native listener or a third-party library calls
stopPropagationon an element below the root. - If a handler fires twice in a portal setup, check whether both the portal content and its React parent respond to the same event.
- If
onScrollon a wrapper does nothing, move it to the element that scrolls. - If a document-level listener stops firing for clicks on certain elements, look for React
stopPropagationcalls. Since React 17 they do reachdocument. - If two React roots are nested, events bubble from the inner root's tree to the outer root's tree. Each root's container handles its own dispatch.
Exercises
Exercise
A component renders <button onClick={e => e.stopPropagation()}>. A separate effect adds a click listener to document. In React 16 the document listener still runs when the button is clicked. Why does it not run in React 17 and later?
Show answer
In React 16, React's own listener was on document, and stopPropagation does not block other listeners on the same node, so the effect's listener still ran. In React 17 and later, React's listener is on the root container, below document. Calling stopPropagation there stops the native event before it bubbles up to document.
Exercise
A native click listener is added with addEventListener to a <div> inside a React app. It calls e.stopPropagation(). A child <button> inside that div has a React onClick. What happens when the button is clicked, and why?
Show answer
The React onClick never runs. React handlers run only when the native event reaches the root container. The native listener on the div runs first and stops the event before it gets there.