SamTaps
SamTaps

Reputation: 63

React index as key, is this a good practice? or should I use react-uuid?

Hi have a list of items that need to be rendered as a group of buttons, I just want to know which is the good and simplest solution.

first option is just use the key as item key


const sampleoutput =[];
for (const [key, value] of Object.entries(sampleItem)) {
    sampleoutput.push(<li>
       <a key={key}
          href="#!"
          onClick={value.onClick}
       >
           {value.title}
       </a>
    </li>);
}

the second solution is to use react-uuid

import uuid from "react-uuid";
sampleItem.map((value) => {
    return (<li>
       <a key={uuid()}
          href="#!"
          onClick={value.onClick}
       >
           {value.title}
       </a>
    </li>);
})

I want also to consider the performance, the second option has another set of processes to generate a key. I am a little concerned with the first option even it is much simpler because of this article https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

Thank you in advance for your advice.

Upvotes: 2

Views: 2433

Answers (3)

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

React expects stable static key which will last till component life 
Using this key, it decide whether new component instance need to
create or  have to update existing component instance property.

react-uuid will generate dynamic key whenever you make a call to uuid() and it will regenerate on every rendering.

Dynamically generated new key will cause to create a new component instance every time whenever there is re-rendering happened.

It's better to create a key from collection only which does not changes and exist there until data exist in collection.

Try to avoid react-uuid and use first approach.

Upvotes: 3

Gaurav Roy
Gaurav Roy

Reputation: 12215

I wouldnt use index as key because

reordering a list, or adding and removing items from a list can cause issues with the component state, when indexes are used as keys. If the key is an index, reordering an item changes it. Hence, the component state can get mixed up and may use the old key for a different component instance.

Therefore, avoid this practice, and make sure unique ids are generated to be assigned as key.

So as you mentioned UUid are the best. source for unique generation of keys

hope it helps. feel free for doubts

Upvotes: 1

Jam3sHalliday
Jam3sHalliday

Reputation: 31

My opinion, be careful when you want to use key = index, some methods can mutate your array (slice / splice), and index will be mess. Just my opinion, bro.

Upvotes: 1

Related Questions