DEV Community

Discussion on: Rendering Arrays in React

Collapse
jeremydmarx813 profile image
Jeremy Marx

Great article, but you really shouldn't use the array index of the element as the key for a react element. It can cause issues with the diffing process if the array is modified. Better to use a random number or something, like with the uuid package.

Collapse
ajithmadhan11 profile image
Ajithmadhan Author

That's a nice catch! Thank you!

Collapse
anushibin007 profile image
Anu Shibin Joseph Raj

Ahh so this must be the culprit in my issue. I have seen that when a single object in my array changes, the whole mapped output refreshes. Could this be because I am not using an unique ID?

And I think this also means that I have to modify my array to look something like this:

const animalList=[
{id: 'a5cr', name: 'Lion'},
{id: 'hh4l', name: 'Tiger'},
{id: 'as78', name: 'Elephant'},
{id: '4ert', name: 'Giraffe'}
];

Am I right?

Collapse
jeremydmarx813 profile image
Jeremy Marx

Yea, that's the idea. I would use a package like uuid to generate the ids, since the amount on items in the array could grow.