Event delegation is a technique where you handle events on a parent element instead of attaching individual event listeners to each child element. This is particularly useful when you have many dynamic elements, like items in a list.
1. Better Performance:
Using one event listener for many items will increase performance due to using of less memory than adding a listener to each item, especially if you have a lot of items or keep adding new ones.
2. Easier to Manage:
You only need to write the code for handling the event once in the parent element. This makes your code simpler and easier to maintain.
3. Works with New Items:
If you add or remove items in the list, the event listener still works without any extra effort. You don’t need to add or remove listeners when the list changes.
import React from 'react';
function ButtonList({ items }) {
return (
<div>
{items.map(item => (
<button key={item.id} onClick={() => alert(`Clicked: ${item.name}`)}>
{item.name}
</button>
))}
</div>
);
}
export default ButtonList;
Each button has its own onClick listener. If you have many buttons, this can slow things down.
import React from 'react';
function ButtonList({ items }) {
const handleClick = (event) => {
if (event.target.tagName === 'BUTTON') {
alert(`Clicked: ${event.target.textContent}`);
}
};
return (
<div onClick={handleClick}>
{items.map(item => (
<button key={item.id}>
{item.name}
</button>
))}
</div>
);
}
export default ButtonList;
Here is only one onClick listener on the parent <div>. When you click a button, the event goes up to the parent, which then checks what was clicked.