0 day streak
javascript / expert
Snippet

Performance Optimization via Ref-Based Event Delegation

In large lists, attaching an onClick handler to every item consumes significant memory. Using a single listener on a parent ref via event delegation is much more efficient.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function LargeList({ items }) {
const listRef = useRef(null);
const handleClick = (e) => {
const item = e.target.closest('[data-id]');
if (item) {
console.log('Clicked item ID:', item.dataset.id);
}
};
return (
<ul ref={listRef} onClick={handleClick}>
{items.map(it => (
<li key={it.id} data-id={it.id}>{it.label}</li>
))}
</ul>
);
}
react
Breakdown
1
onClick={handleClick}
A single event listener attached to the container rather than N items.
2
e.target.closest('[data-id]')
Uses DOM traversal to find the relevant item metadata regardless of deep nesting.
3
item.dataset.id
Retrieves business logic data directly from the DOM attribute.