Why doesn't React use the object reference as key?

289
November 30, 2017, at 09:48 AM

When rendering a list of items, React uses the index of each item as a default key, if none is supplied.

return <div> 
    {this.props.shows.map(show => <ShowComp title = {show.title}/>)} 
</div>;

But why doesn't React use the JS object reference of each item instead? Seems to me like a much safer option, as it would not cause re-rendering of any of the items if the list order changes (as opposed to the index approach).

I'm relatively new to React, so I'm sure there's an underlying reason.

In Angular, ngFor (which renders a list of elements, similar to mapping object to React elements), it also has a trackBy configuration option (which is the equivalent of key in React). However, if it's not supplied, it uses the object references as an identifier, which seems more natural.

Answer 1

The reason why it's not using the reference of the object by default is all React's developpers choice.

Keep in mind it doesn't have to be unique across all the items, it has to be unique across the siblings of each item.

As shown here : https://reactjs.org/docs/reconciliation.html#keys

You could definitely use a not so unique key that's only unique across siblings.

Also, is using the reference of the object faster than most small integer found in unique ids ?

Rent Charter Buses Company
READ ALSO
Store latitude and longitude in a database using Google maps geometry

Store latitude and longitude in a database using Google maps geometry

When an user puts in their adress like: Oosterdok 2, 1011 VX Amsterdam and press save adressIt will get the latitude and the longitude and shows it in a li table (to check if its the right one)

276
JavaScript - 100 million * 100 iterations performance

JavaScript - 100 million * 100 iterations performance

I have a code which I need to execute 100m times and gather statistics from each iteration

284
Owl carousel w/ owl-filter.js duplicating images, even when loop is false

Owl carousel w/ owl-filter.js duplicating images, even when loop is false

I'm trying to create a product image slider which reacts to a variant drop down selectorI decided to try and use owl carousel and found owl-filter

455