DEV Community

Cover image for Should I use event delegation in React?
Thawsitt Naing
Thawsitt Naing

Posted on

40 4 1

Should I use event delegation in React?

What is event delegation?

Event delegation is a performance optimization method in the world of Javascript. Let's say you have an unordered list <ul> with 1000 list items, and you want to do something each time a list item is clicked. With event delegation approach, instead of adding one event listener to each of the child items, you only add 1 event listener to the parent <ul>. It is a neat approach. You can read more about it here.

Should I use event delegation in React?

The short answer is "No". It does not give you any noticeable performance benefit. The reason is that React already does this performance optimization internally. If you don't believe me, check out the answer by Dan Abramov here.

Performance benchmark

I wanted to test this myself. So, I created a test project with 3000 buttons. When a button is clicked, we change its state to "Selected" in the parent container, and its background color changes.

You can check out the two demos here. Continue reading for the source code.

No event delegation - 3000 event listeners

We attach an onClick handler to each of the buttons.

// selectedItems = new Set([1, 2, 3])
// ids = [0, 1, 2, ..., 2999]

{ids.map((id) => (
  <FancyButton
    key={id}
    id={id}
    label={id}
    isSelected={selectedItems.has(id)}
    onClick={() => handleClick(id)}
  />
))}
  • See full source code here.

With event delegation - 1 event listener

Here, we attach only one onClick handler to the parent div.

const handleClick = (event) => {
  // Get id from button element
  const id = event.target.id;
  setSelectedItems((prevState) => new Set([...prevState, id]));
};


<div className="container" onClick={handleClick}>
  {ids.map((id) => (
    <FancyButton
      key={id}
      id={id}
      label={id}
      isSelected={selectedItems.has(id)}
    />
  ))}
</div>
  • See full source code here.

Results

race-start

Who will be the winner?

Test 1. First load

off-start

on-start

Test 2. Interaction

off-interaction

on-interaction

Test 3. Heap snapshot

off-snapshot

on-snapshot

Test 4. Event Listeners count

off-count

on-count

Conclusion

We didn't find any noticeable performance difference between the two. React is already optimized in most cases, so you can focus on the awesome features you are shipping. 🚀🚀🚀

Feel free to benchmark the two demos yourself and let me know if you find any different results.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (4)

Collapse
 
anuraghazra profile image
Anurag Hazra

This is helpful.

Collapse
 
bravemaster619 profile image
bravemaster619

Nice article! I once made a big table with Vue and the speed was notoriously slow, although each td has almost the same event. Do you think Vue has optimization similar to React?

Collapse
 
thawsitt profile image
Thawsitt Naing

I haven't used Vue before, but it seems like Vue doesn't do this optimization internally. You might find this answer helpful.

Collapse
 
waliurjs profile image
Mahmud

God bless you!!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️