When we build web applications, handling user interactions (like clicks, key presses, or form submissions) is a crucial part of the job. But the way we handle these events has changed a lot over the years. One of the key improvements is something called event delegation.
Let’s walk through this concept step by step — starting from how we used to do it before delegation existed, and how React improved it.
📍 Before Event Delegation: Direct Event Binding
In the early days of JavaScript, if you wanted to make multiple buttons respond to clicks, the straightforward way was to attach an event listener directly to each button.
Example:
👉 What this means:
- Every element gets its own event listener.
- If you had 1,000 buttons, you’d end up with 1,000 listeners in memory.
⚠️ Problems with this old method:
- Performance issues: Too many listeners slow down the page.
- Memory overhead: Each listener takes space.
- Maintenance headache: If you remove an element, you also need to remove its listener.
- Cross-browser quirks: Different browsers handled events differently.
Enter Event Delegation
Here’s where event delegation comes in. Instead of attaching listeners to every element, you attach one listener to a parent element (or even the document).
This works because of event bubbling:
When you click a child element, the event travels (or “bubbles up”) through its ancestors until it reaches the root.
The parent can “catch” that event and figure out which child triggered it.
Example:
👉 What changed:
One single event listener on the parent handles all child button clicks.
Adding or removing buttons doesn’t require attaching/removing new listeners.
✅ Improvements:
- Better performance.
- Less memory usage.
- Easier DOM updates.
📍 React’s Approach: Synthetic Events + Delegation
React takes this idea further. When you write:
…it looks like you’re attaching a listener directly to the button. But under the hood, React does not put a listener on every button.
🔧 What React does instead:
- React attaches a single listener (per event type, like click) at the root level.
- When a real DOM event happens, React intercepts it.
- React creates a SyntheticEvent — a wrapper that normalizes browser differences (so you don’t worry about inconsistencies like event.target vs event.srcElement).
- React dispatches the event internally to the correct component’s onClick handler.
🚀 Final Thoughts
Event delegation transformed how we handle user interactions. Instead of cluttering every element with its own event listener, we now rely on bubbling and centralized listeners.
React supercharged this by introducing its Synthetic Event system, making event handling:
- Faster
- Safer across browsers
- Easier to maintain
So next time you write an onClick in React, remember—it’s not attached to your button directly. React is quietly handling it for you through delegation.
Top comments (0)