3
votes

I use React to render a list of data, but each item in the data have not been assigned id or uuid or something like identify property. Can I use the item index as the key? like:

data.map((item, index) => {
    <Item key={index}></Item>
})

What I concerned is if some other list on the page also use the order index as the child component key, would it matter? Should the key be a unique identify?

2

2 Answers

2
votes

The key only needs to be unique to that list.

I also had that worry initially.

From the official docs:

Remember that the key only has to be unique among its siblings, not globally unique.

Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many nodes to be unnecessarily re-created, which can cause performance degradation and lost state in child components.

Read more here: Reconciliation - Keys

1
votes

You can do this if you not going to move your elements within list. Your elements will have different indices each time you move them, so react can't track which elements a moved and which just changed their data.

indices must be unique whithin their lists, they may intersect with other lists.