Should I use event delegation in React?

thawsitt

Thawsitt Naing

Posted on May 2, 2020

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
thawsitt
Thawsitt Naing

Posted on May 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About