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

Reactjs

Reactjs Problem Overview


Problem is the following:

I have data in form of a list of a few thousand elements. Some of them are duplicates, and there might be the chance of having duplicate keys as well then. Because I have no real "ID" or anything which would give me the opportunity to give all elements their id as unique keys, is it okay to use Math.random() instead?

As far as I understood, the keys are mainly used by react to differentiate the components. I think as far as I don't really have anything to do with the keys in my code, this should go fine? To ensure that there will be no duplicate number I might as well divide two math randoms with each other to get an almost certainly unique key.

Is this a good practice? Can I use this without having to worry about anything?

Reactjs Solutions


Solution 1 - Reactjs

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)

Solution 2 - Reactjs

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()}

Solution 3 - Reactjs

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.

Solution 4 - Reactjs

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

Solution 5 - Reactjs

> Is this a good practice? Can I use this without having to worry about anything?

No and no.

> 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.

Let me illustrate this with a simple example.

class Input extends React.Component {
  handleChange = (e) =>  this.props.onChange({
    value: e.target.value,
    index: this.props.index
  });
  render() {
    return (
      <input value={this.props.value} onChange={this.handleChange}/>  
    )
  }
};

class TextInputs extends React.Component {
  state = {
    textArray: ['hi,','My','Name','is']
  };
  handleChange = ({value, index}) => {
    const {textArray} = this.state;
    textArray[index] = value;
    this.setState({textArray})
  };
  render(){
  return this.state.textArray.map((txt, i) => <Input onChange={this.handleChange} index={i} value={txt} key={Math.random()}/>)
  // using array's index is not as worse but this will also cause bugs.  
  // return this.state.textArray.map((txt, i) => <Input onChange={this.handleChange} index={i} value={txt} key={i}/>)                 
  };
};

Why can't i type in more than one character in the inputs you ask?

It is because I am mapping multiple text inputs with Math.random() as key prop. Every time I type in a character the onChange prop fires and the parent component's state changes which causes a re-render. Which means Math.random is called again for each input and new key props are generated.So react renders new children Input components.In other words every time you type a character react creates a new input element because the key prop changed.

Read more about this here

Solution 6 - Reactjs

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.

You should add a key to each child as well as each element inside children.

This way React can handle the minimal DOM change.

Please go through the https://reactjs.org/docs/reconciliation.html#recursing-on-children. Here you will get best explanation with example of code.

Solution 7 - Reactjs

I had a use case where I am rendering a list of tiles based on data fetched from a remote API. For example, the data looks like this -

[
  {referrals: 5, reward: 'Reward1'},
  {referrals: 10, reward: 'Reward2'},
  {referrals: 25, reward: 'Reward3'},
  {referrals: 50, reward: 'Reward4'}
]
  • This list can be modified on the client-side where a random entry (tile) in the list can be spliced/removed, or a new entry (tile) can be added at the end of the list.

  • There could be duplicate entries in this list so I cannot create a hash/unique key based on the content of the list entry.

Initially, I tried using array index as a key to render the tiles but in this case what ends up happening is, if I splice the entry at index 3 for example, then the entry at index 4 takes its place at index 3, and for React, since key 3 is intact, while rendering, it just removes the tile at index 4 while keeping the original tile at index 3 still visible, which is undesired behavior.

So based on the above ideas shared by @josthoff and @Markus-ipse I used a client-side self-incrementing counter as a key (Check https://stackoverflow.com/a/46632553/605027)

When data is initially fetched from the remote API, I add a new key attribute to it

let _tiles = data.tiles.map((v: any) => (
  {...v, key: this.getKey()}
))

So it looks like below

[
  {referrals: 5, reward: 'Reward1', key: 0},
  {referrals: 10, reward: 'Reward2', key: 1},
  {referrals: 25, reward: 'Reward3', key: 2},
  {referrals: 50, reward: 'Reward4', key: 3}
]

When adding a new entry (tile), I make another call to this.getKey(). By doing this, every entry (tile) has a unique key and React behaves as intended.

I could've used a random hexadecimal key or UUID generator here but for simplicity I went ahead with self-incrementing counter.

Solution 8 - Reactjs

I think its not correct to give Math.random() for components keys, reason is when you generate random number it is not guaranteed not to get same number again. It is very much possible that same random number is generated again while rendering component, So that time it will fail.

Some people will argue that if random number range is more it is very less probable that number will not be generated again. Yes correct but you code can generate warning any time.

One of the quick way is to use new Date() which will be unique.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSossenbinderView Question on Stackoverflow
Solution 1 - ReactjsMarkus-ipseView Answer on Stackoverflow
Solution 2 - ReactjsjosthoffView Answer on Stackoverflow
Solution 3 - ReactjsGlen SwiftView Answer on Stackoverflow
Solution 4 - ReactjsKhalid AzamView Answer on Stackoverflow
Solution 5 - Reactjs Shady PillgrimView Answer on Stackoverflow
Solution 6 - ReactjsPrajakta SalokheView Answer on Stackoverflow
Solution 7 - ReactjsMadhurView Answer on Stackoverflow
Solution 8 - ReactjsAnil KumarView Answer on Stackoverflow