Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 15, 2021 01:51 pm GMT

A react optimization that takes 2 minutes to implement

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.


Original Link: https://dev.to/abhinavsachdeva/a-react-optimization-that-takes-2-minutes-to-implement-43g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To