hh54188
hh54188

Reputation: 15646

React.js: the key value in each child component should be unique?

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?

Upvotes: 3

Views: 681

Answers (2)

ctrlplusb
ctrlplusb

Reputation: 13147

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

Upvotes: 2

Maxx
Maxx

Reputation: 1748

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.

Upvotes: 1

Related Questions