Events

Synthetic events, delegation at the root, passing handlers down.

Builds on Components and props.

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.

Who is actually listening?
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>;
}
Nothing logged yet.

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:

  1. One listener per event type instead of one per element. A table with 5,000 rows and an onClick on each would otherwise mean 5,000 addEventListener calls on mount and 5,000 removals on unmount.
  2. 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.
  3. One event shape everywhere. React normalizes browser differences behind a single SyntheticEvent API.

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.

A toy event delegator
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)![type](e);
    }
  });
}

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));
Nothing logged yet.

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.

One listener at the root
The DOMdocumentdiv#rootReact's listeners live herediv onClick={toolbar}button onClick={save}React's dispatch at the rootNothing happens until an event reaches the root.
Step 1 of 5

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. A stopPropagation in one app affected the other. Now each root handles its own events.
  • e.stopPropagation() now does what people expect to native listeners on document. When the handlers ran at document, the native event had already reached document, so stopping it was too late. Now React stops the native event at the root, before it gets to document.

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:

  • onChange fires on every keystroke for text inputs. React's onChange listens to the native input event. The native change event, which fires only when the edit is committed (usually on blur), is not what you get.
  • onWheel, onTouchStart and onTouchMove are passive. React registers those root listeners with passive: true, so e.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.
  • onFocus and onBlur bubble. React implements them with the native focusin and focusout events. Check e.currentTarget.contains(e.relatedTarget) to ignore focus moving between children.
  • onScroll doesn't bubble (since React 17). A scroll inside a child no longer fires a parent's onScroll.
  • onMouseEnter and onMouseLeave don'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.

Reading the event after a delay
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} />;
}
Nothing logged yet.

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 render

The 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.

Handlers as props
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 its href. It has nothing to do with propagation.
PredictWho logs, and in what order?

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>
  );
}
Nothing logged yet.
Fix itDelete also opens the book

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#

Build itAdd stopPropagation to the toy

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)![type](e);
    }
  });
}
Nothing logged yet.
Quick checkonChange

When does React's onChange fire for a text input?

Explain it out loudHow do React events work?

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

Say it in 30 seconds

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?

basic

Walk me through what happens when a user clicks a button with an onClick in React.

intermediate

Why did React 17 move event delegation from document to the root container?

senior

What was event pooling, and what happened to it?

intermediate

What happens when you mix native addEventListener calls with React handlers?

senior

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.
  • onChange fires on every edit, onFocus and onBlur bubble, onScroll doesn't.
  • Pass handlers, don't call them. Child components report through onSomething props; parents decide what it means.
  • stopPropagation stops the rest of React's pass and the native event at the root, not native listeners that ran earlier inside the tree.

Sources#