Components describe UI from props. To be useful they also have to respond to people: clicks, typing, submits. In the toy React from Part 2, the simplest way to wire that up was to see a prop like onClick and call addEventListener on the DOM node. Real React doesn't do that, and the difference explains several behaviors that show up in interviews: why e.nativeEvent exists, why stopPropagation sometimes doesn't stop a listener you added by hand, and why old code calls e.persist().
This chapter is about how events get from the browser to your function, and how you pass handlers around a component tree.
The problem: where is the listener?#
Click the button below and read the console. e.currentTarget is the element whose handler is running. e.nativeEvent is the browser's real event underneath.
import type { MouseEvent } from "react";
export default function App() {
function handleClick(e: MouseEvent<HTMLButtonElement>) {
console.log("React currentTarget:", e.currentTarget.tagName);
const native = e.nativeEvent.currentTarget as HTMLElement;
console.log("native currentTarget:", native.tagName + "#" + native.id);
console.log("native eventPhase:", e.nativeEvent.eventPhase, "(3 means bubbling)");
}
return <button onClick={handleClick}>Click me</button>;
}React says the current target is the BUTTON. The browser says the listener that's running belongs to DIV#root, the container you passed to createRoot, and that the event is in its bubbling phase. Your function isn't attached to the button at all. (React does set an empty onclick no-op on elements with onClick, a workaround so mobile Safari dispatches clicks on non-interactive elements, but nothing on the button calls your code.) React put one listener on the root and is pretending, convincingly, that your handler was attached to the button.
Why go to that trouble? Three reasons:
- One listener per event type instead of one per element. A table with 5,000 rows and an
onClickon each would otherwise mean 5,000addEventListenercalls on mount and 5,000 removals on unmount. - Control. Because every event passes through React first, React can batch the state updates your handlers make (you'll see this in State) and give updates from a click a higher priority than updates from a mouse move. That priority idea comes back in Rendering and scheduling.
- One event shape everywhere. React normalizes browser differences behind a single
SyntheticEventAPI.
Build it: delegation in thirty lines#
Here's the mechanism, without React. Handlers are stored in a WeakMap keyed by element (standing in for the props React keeps on each fiber). One listener on the root walks from the event's target up to the root, collects handlers, and calls them with a fake event whose currentTarget changes as it goes.
type ToyEvent = { type: string; target: Element; currentTarget: Element | null; nativeEvent: Event };
type Handler = (e: ToyEvent) => void;
const handlers = new WeakMap<Element, Record<string, Handler>>();
function setHandler(el: Element, type: string, fn: Handler) {
handlers.set(el, { ...handlers.get(el), [type]: fn });
}
function listen(root: Element, type: string) {
root.addEventListener(type, (native) => {
// 1. Collect handlers from the target up to the root.
const path: Element[] = [];
let node = native.target as Element | null;
while (node && node !== root) {
if (handlers.get(node)?.[type]) path.push(node);
node = node.parentElement;
}
// 2. Call them innermost first with one shared event object.
const e: ToyEvent = { type, target: native.target as Element, currentTarget: null, nativeEvent: native };
for (const el of path) {
e.currentTarget = el;
handlers.get(el);
}
});
}
const root = document.getElementById("root")!;
listen(root, "click");
setHandler(document.getElementById("save")!, "click", (e) => console.log("save, currentTarget =", e.currentTarget!.id));
setHandler(document.getElementById("toolbar")!, "click", (e) => console.log("toolbar, currentTarget =", e.currentTarget!.id));React's real version differs in the details you'd expect: it walks the fiber tree through return pointers rather than the DOM (which is why events from a portal bubble to the portal's React parent, covered in Portals and Profiler), it runs a capture pass for onClickCapture props, and it maps each native event to one or more React events. The shape is the same.
createRoot(container) attaches one native listener per event type to the root container, for both capture and bubble phases. Your onClick function is never attached to the button itself.
Delegation at the root, since React 17#
Before React 17, React attached its listeners to document. React 17 moved them to the root container. The change sounds cosmetic, but it fixed two real problems:
- Several React apps on one page, or a React app inside a page run by something else, used to fight over
document. AstopPropagationin one app affected the other. Now each root handles its own events. e.stopPropagation()now does what people expect to native listeners ondocument. When the handlers ran atdocument, the native event had already reacheddocument, so stopping it was too late. Now React stops the native event at the root, before it gets todocument.
At creation, createRoot subscribes the container to every event React delegates, in both phases. (A few events that don't bubble reliably, like scroll and media events, also get a listener on the element itself.) So a component that mounts later doesn't add listeners for ordinary events like clicks; the root already hears them.
The SyntheticEvent#
Your handler receives a SyntheticEvent: a wrapper with the standard DOM event interface (target, currentTarget, preventDefault(), stopPropagation(), key, clientX and so on) that behaves the same across browsers. The browser's event is always available as e.nativeEvent.
A few behaviors differ from the raw DOM on purpose, and interviewers like them:
onChangefires on every keystroke for text inputs. React'sonChangelistens to the nativeinputevent. The nativechangeevent, which fires only when the edit is committed (usually on blur), is not what you get.onWheel,onTouchStartandonTouchMoveare passive. React registers those root listeners withpassive: true, soe.preventDefault()in them can't stop scrolling (the browser warns instead). If you really need to block scrolling, add a native listener with{ passive: false }from an effect or ref callback.onFocusandonBlurbubble. React implements them with the nativefocusinandfocusoutevents. Checke.currentTarget.contains(e.relatedTarget)to ignore focus moving between children.onScrolldoesn't bubble (since React 17). A scroll inside a child no longer fires a parent'sonScroll.onMouseEnterandonMouseLeavedon't bubble, matching the DOM.
React 19.3 React 19.3 added a submitter property on submit events (the button that triggered the submit) and the onFullscreenChange and onFullscreenError events.
The end of event pooling#
Old React (16 and earlier) reused SyntheticEvent objects: after your handler returned, React reset every field to null and put the object back in a pool. Reading e.target inside a setTimeout or after an await gave you null, and the fix was e.persist(). React 17 removed pooling because it saved almost nothing in modern browsers and confused everyone. e.persist() still exists and does nothing.
import type { ChangeEvent } from "react";
export default function App() {
function handleChange(e: ChangeEvent<HTMLInputElement>) {
const now = e.target.value;
setTimeout(() => {
// In React 16 e.target would be null here. Since 17 it's fine.
console.log("typed:", now, "| later:", e.target.value);
}, 300);
}
return <input placeholder="Type here" onChange={handleChange} />;
}Notice the second value: it's what the input holds now, 300 milliseconds later, not when the event fired. The event object survives, but e.target is a live DOM node. Copy values out of the event when you need them as they were.
Passing handlers#
A handler is a function you pass, not a function you call:
<button onClick={handleClick}>Save</button> // pass the function
<button onClick={() => remove(book.id)}>Delete</button> // wrap to pass arguments
<button onClick={handleClick()}>Oops</button> // calls it during renderThe last line runs handleClick while rendering and passes its return value as the handler. If handleClick sets state, that's an infinite render loop.
Handlers are usually defined inside the component so they can read props and state. Components pass behavior down to children the same way they pass data, as props. The convention: props are named onSomething, and the functions that implement them are named handleSomething.
import { books } from "guide-tools";
type Book = (typeof books)[number];
type BookRowProps = {
book: Book;
onSelect: (id: number) => void; // typing pattern: describe what the child calls
};
function BookRow({ book, onSelect }: BookRowProps) {
// The child doesn't know what "select" means. It just reports it.
return (
<li>
{book.title} <button onClick={() => onSelect(book.id)}>Details</button>
</li>
);
}
export default function App() {
function handleSelect(id: number) {
const book = books.find((b) => b.id === id)!;
alert(`${book.title} by ${book.author}, ${book.year}`);
}
return (
<ul>
{books.slice(0, 3).map((b) => (
<BookRow key={b.id} book={b} onSelect={handleSelect} />
))}
</ul>
);
}Typing patterns. React's event types live in the react package and are generic over the element: MouseEvent<HTMLButtonElement>, ChangeEvent<HTMLInputElement>, KeyboardEvent<HTMLInputElement>, and for onSubmit either SubmitEvent<HTMLFormElement> in current types or the older, now deprecated FormEvent<HTMLFormElement> (TypeScript with React has the details). Import them as types (import type { MouseEvent } from "react"), and don't confuse them with the DOM's global MouseEvent, which is the native event. For a prop that takes a whole handler, MouseEventHandler<HTMLButtonElement> is shorthand for (e: MouseEvent<HTMLButtonElement>) => void. For custom callbacks like onSelect, type the arguments your component actually passes; don't leak the event object to parents that don't need it. When you write a handler inline, you don't need any of this: TypeScript infers e from the prop.
Propagation and default behavior#
React events propagate through the React tree the way DOM events propagate through the DOM: a capture phase from the root down (props ending in Capture, like onClickCapture) and a bubble phase from the target up (onClick). Each handler can call:
e.stopPropagation(): no more React handlers run for this event after the current one. React also stops the native event at the root.e.preventDefault(): cancel the browser's default action, like a form submit navigating or a link following itshref. It has nothing to do with propagation.
The app has a native listener on document, a capture handler on the outer div, and bubble handlers on both. Predict the console output when you click the button. Then predict it again with the stopPropagation() line uncommented.
document.addEventListener("click", () => console.log("document (native)"));
export default function App() {
return (
<div
onClickCapture={() => console.log("div capture")}
onClick={() => console.log("div bubble")}
>
<button
onClick={(e) => {
console.log("button");
// e.stopPropagation();
}}
>
Click
</button>
</div>
);
}Clicking a row selects that book. Each row also has a Delete button, but clicking it selects the book too. Make Delete only delete. (This uses useState, covered fully in the next chapter.)
import { useState } from "react";
import { books } from "guide-tools";
export default function App() {
const [list, setList] = useState(books.slice(0, 4));
const [selected, setSelected] = useState<string | null>(null);
return (
<>
<p>Selected: {selected ?? "none"}</p>
<ul>
{list.map((book) => (
<li key={book.id} onClick={() => setSelected(book.title)} style={{ cursor: "pointer" }}>
{book.title}{" "}
<button
onClick={() => {
setList(list.filter((b) => b.id !== book.id));
}}
>
Delete
</button>
</li>
))}
</ul>
</>
);
}Pitfalls#
Check your understanding#
The toy delegator from earlier calls every handler on the path. Add a stopPropagation() method to the event it creates. When a handler calls it, no further handlers on the path should run, and the native event should stop too, so listeners above the root don't hear it. Export listen and setHandler from delegate.ts; the checks import them.
export type ToyEvent = {
type: string;
target: Element;
currentTarget: Element | null;
nativeEvent: Event;
stopPropagation: () => void;
};
type Handler = (e: ToyEvent) => void;
const handlers = new WeakMap<Element, Record<string, Handler>>();
export function setHandler(el: Element, type: string, fn: Handler) {
handlers.set(el, { ...handlers.get(el), [type]: fn });
}
export function listen(root: Element, type: string) {
root.addEventListener(type, (native) => {
const path: Element[] = [];
let node = native.target as Element | null;
while (node && node !== root) {
if (handlers.get(node)?.[type]) path.push(node);
node = node.parentElement;
}
const e: ToyEvent = {
type,
target: native.target as Element,
currentTarget: null,
nativeEvent: native,
stopPropagation: () => {
// TODO
},
};
for (const el of path) {
e.currentTarget = el;
handlers.get(el);
}
});
}When does React's onChange fire for a text input?
An interviewer asks: "When I write onClick on a button, does React call addEventListener on that button? Walk me through what happens on a click."
Interview angle
React doesn't put listeners on your elements. Since React 17, React attaches one listener per event type to the root container (createRoot does this today), in both phases. On a click, the native event bubbles to the root, React finds the target's fiber, walks up the tree collecting onClickCapture and onClick props, and calls them with a SyntheticEvent that wraps the native one. That gives fewer listeners, consistent behavior across browsers, and lets React batch and prioritize updates. Event pooling is gone since 17, and stopPropagation stops React's pass plus the native event at the root.
What is a SyntheticEvent?
Walk me through what happens when a user clicks a button with an onClick in React.
Why did React 17 move event delegation from document to the root container?
What was event pooling, and what happened to it?
What happens when you mix native addEventListener calls with React handlers?
Recap#
- React doesn't attach listeners to your elements. Since React 17, one listener per event type lives on the root container, and React dispatches to handlers by walking the fiber tree.
- Handlers receive a SyntheticEvent with the standard interface and the real event at
e.nativeEvent. Pooling is gone, so the object is safe to keep, but copy DOM values before async work. onChangefires on every edit,onFocusandonBlurbubble,onScrolldoesn't.- Pass handlers, don't call them. Child components report through
onSomethingprops; parents decide what it means. stopPropagationstops the rest of React's pass and the native event at the root, not native listeners that ran earlier inside the tree.
Sources#
- react.dev: Responding to events
- react.dev: Common components: React event object
- react.dev blog: React v17.0 (delegation at the root, removal of event pooling, onScroll no longer bubbles)
- Facts checked November 24, 2026.