A react optimization that takes 2 minutes to implement
Abhinav Sachdeva
Posted on May 15, 2021
Our applications usually have a list component (which one doesn't?), even the todo apps have it, right?
There's a good proabability that something happens when the user clicks on a list item. There's also a good probabilty that the handler is not implemented the "right" way.
const handleClick = (item) => { }
return <div className="listContainer">
<ul>
{
data.map((item,idx) => (
<li key={idx} onClick={() => handleClick(item)}>{item}</li>
))
}
</ul>
</div>;
Maybe you've already guessed it, we're attaching a new function to each list item. And what's more, it happens on each render!
We can make use of event bubbling here to fire a common handler for every list item.
Here's how to refactor :
- Remove the
onClick
from the list. - The handler function would now receive the item index instead of the entire item, so we need to refactor any code inside the handler assuming we have access to the index, not the array element.
- Attach a
data
attribute to each list item while rendering. Thee value of this attribute would be the array item index (or even any property from inside of the item itself!). - Attach an
onClick
to the parent of the list items, it could be the parent at any level.
Here's how our code looks after the refactor:
const handleClick = (item) => {console.log(item)}
return <div className="listContainer">
<ul onClick={(e) => handleClick(e.target.dataset.id)}>
{
data.map((item,idx) => (
<li key={idx} data-id={idx}>{item}</li>
))
}
</ul>
</div>;
This didn't take too long but benefit get big especially with larger lists.
💖 💪 🙅 🚩
Abhinav Sachdeva
Posted on May 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.