event delegation
Handling events for many child elements with one listener on a shared ancestor, using event.target to find which child was involved.
In more detail
Instead of hundreds of listeners, a single one on the list checks event.target.closest('button.del') and reads the row's data attribute. Items added later work automatically, and removed items leave no listeners behind. Use focusin and focusout, not focus and blur, since only they bubble.
Example
React attaches one listener per event type to each root container; since React 17 not to the document, so several React apps can share a page.Related terms
- event bubbling — The way an event on an element also triggers handlers on its parent elements, one level at a time up the tree.
- Element.closest() — The DOM method that starts at an element and walks up through its ancestors, returning the first one, itself included, that matches a selector.
- event.target — The event property holding the element where the event actually started, such as the icon inside a button that was clicked.
- data attribute — A custom HTML attribute whose name starts with data-, such as data-theme="dark", used to store extra information on an element.
- focusin and focusout — The bubbling versions of the focus and blur events, which fire as focus moves into or out of an element and travel up to its ancestors.
- root container — The existing page element, often <div id="root">, into which React renders an application.
- SyntheticEvent — The event object React passes to your handlers, a wrapper around the browser native event that behaves the same in every browser.
Taught in
- Event Delegation: Memory-Efficient Interaction Handlers — Frontend Architecture & Web Platform
- Diffing Algorithm: Element Type Shifts And Subtree Tear Down — React 19 & Modern Component Architecture
- SyntheticEvent System: Event Delegation in Modern React — React 19 & Modern Component Architecture
- Higher-Order Components And Render Props: Tradeoff Analysis — React 19 & Modern Component Architecture