When giving unique keys to components, is it okay to use Math.random() for generating those keys?

Every time a component's key changes React will create a new component instance rather than update the current one, so for performance's sake using Math.random() will be sub-optimal to say the least.

Also if you'll be reordering your list of components in any way, using the index as key will not be helpful either since the React reconciler will be unable to just move around existing DOM nodes associated with the components, instead it will have to re-create the DOM-nodes for each list item, which, once again will have sub-optimal performance.

But to reiterate, this will only be a problem if you will be re-ordering the list, so in your case, if you are sure you will not be reordering your list in any way, you can safely use index as a key.

However if you do intend to reorder the list (or just to be safe) then I would generate unique ids for your entities - if there are no pre-existing unique identifiers you can use.

A quick way to add ids is to just map the list and assign the index to each item when you first receive (or create) the list.

const myItemsWithIds = myItems.map((item, index) => { ...item, myId: index });

This way each item get a unique, static id.

tl;dr How to choose a key for new people finding this answer

  1. If your list item have a unique id (or other unique properties) use that as key

  2. If you can combine properties in your list item to create a unique value, use that combination as key

  3. If none of the above work but you can pinky promise that you will not re-order your list in any way, you can use the array index as key, but you are probably better of adding your own ids to the list items when the list is first received or created (see above)


Just implement the following code in your react component...

constructor( props ) {
    super( props );

    this.keyCount = 0;
    this.getKey = this.getKey.bind(this);
}

getKey(){
    return this.keyCount++;
}

...and call this.getKey() every time you need a new key like:

key={this.getKey()}

From react documentation:

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


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

https://facebook.github.io/react/docs/reconciliation.html