This content originally appeared on DEV Community and was authored by Abhinav Sachdeva
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.
This content originally appeared on DEV Community and was authored by Abhinav Sachdeva
Abhinav Sachdeva | Sciencx (2021-05-15T13:51:39+00:00) A react optimization that takes 2 minutes to implement. Retrieved from https://www.scien.cx/2021/05/15/a-react-optimization-that-takes-2-minutes-to-implement/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.