Home > Software engineering >  Properly choosing React keys while rendering items from array
Properly choosing React keys while rendering items from array

Time:09-21

I've been recently studying the importance of elements' keys in React and I'm still a little confused about it.

I have this case where there is datagrid component responsible for presenting data in rows. There is implemented sorting, filtering and pagination. I fetch the rows data from api.

And the question is: How should I properly choose keys for map function elements (rows)?

The thing is that the already fetched row data can change between refreshes (by being edited by other user).

Should I use unique ids for key properties (for instance nanoid) or use row.id?

If I understand it correctly, using row.id would result in no row rerendering for already loaded rows even if some of row data were changed. On the other hand, using unique ids (like nanoid) would make negative impact on performance while sorting, filtering etc...?

Do I get this right, and how to do this properly then?

CodePudding user response:

Keys should always be unique, stable (as mentioned above by Brian), and never manipulated in your code (hence stable).

A unique ID is preferred. I've seen people pass an entire user object as the key. Let along that there might be duplicate users, this could also be an enormous key.

Do not use the index of any array as your key.

CodePudding user response:

I agree to study the key in more details. Here's my understanding.

If I understand it correctly, using row.id would result in no row rerendering for already loaded rows even if some of row data were changed.

This is not true, the purpose of the key is to identify the item location, so when it comes to the reconciliation (convert element into a node), React knows if a node (fiber) can be reused to speed up the update process.

Let's make an example, if initially the the key order is

  1 2 3

And somehow after a re-order, it becomes the following in the new update

  2 1 3

Then React is guided to use the node with key 1 to update the item. The item is updated, and in this case, to the right place. BTW, React doesn't know by default the order of items, to React, they look all similar ;)

I'm only giving you a basic case. But you can make a guess for other cases, ex. with one key missing, or a new key added.

  • Related