Should I use event delegation in React?
Thawsitt Naing
Posted on May 2, 2020
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.
- Without event delegation: https://test-event-delegation-off.now.sh/
- With event delegation: https://test-event-delegation-on.now.sh/
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
Test 1. First load
Test 2. Interaction
Test 3. Heap snapshot
Test 4. Event Listeners 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.
- Without event delegation: ๐ Demo, ๐ฑ Source Code
- With event delegation: ๐ Demo, ๐ฑ Source Code
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
September 24, 2024