Understanding unique keys for array children in React.js Understanding unique keys for array children in React.js reactjs reactjs

Understanding unique keys for array children in React.js


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

This way React can handle the minimal DOM change.

In your code, each <TableRowItem key={item.id} data={item} columns={columnNames}/> is trying to render some children inside them without a key.

Check this example.

Try removing the key={i} from the <b></b> element inside the div's (and check the console).

In the sample, if we don't give a key to the <b> element and we want to update only the object.city, React needs to re-render the whole row vs just the element.

Here is the code:

var data = [{name:'Jhon', age:28, city:'HO'},            {name:'Onhj', age:82, city:'HN'},            {name:'Nohj', age:41, city:'IT'}           ];var Hello = React.createClass({    render: function() {      var _data = this.props.info;      console.log(_data);      return(        <div>            {_data.map(function(object, i){               return <div className={"row"} key={i}>                           {[ object.name ,                             // remove the key                             <b className="fosfo" key={i}> {object.city} </b> ,                              object.age                          ]}                      </div>;              })}        </div>       );    }});React.render(<Hello info={data} />, document.body);

The answer posted by @Chris at the bottom goes into much more detail than this answer. Please take a look at https://stackoverflow.com/a/43892905/2325522

React documentation on the importance of keys in reconciliation: Keys


Be careful when iterating over arrays!!

It is a common misconception that using the index of the element in the array is an acceptable way of suppressing the error you are probably familiar with:

Each child in an array should have a unique "key" prop.

However, in many cases it is not! This is anti-pattern that can in some situations lead to unwanted behavior.


Understanding the key prop

React uses the key prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one. It is also important that these keys remain static throughout all re-renders in order to maintain best performance.

That being said, one does not always need to apply the above, provided it is known that the array is completely static. However, applying best practices is encouraged whenever possible.

A React developer said in this GitHub issue:

  • key is not really about performance, it's more about identity (which in turn leads to better performance). randomly assigned and changing values are not identity
  • We can't realistically provide keys [automatically] without knowing how your data is modeled. I would suggest maybe using some sort of hashing function if you don't have ids
  • We already have internal keys when we use arrays, but they are the index in the array. When you insert a new element, those keys are wrong.

In short, a key should be:

  • Unique - A key cannot be identical to that of a sibling component.
  • Static - A key should not ever change between renders.

Using the key prop

As per the explanation above, carefully study the following samples and try to implement, when possible, the recommended approach.


Bad (Potentially)

<tbody>    {rows.map((row, i) => {        return <ObjectRow key={i} />;    })}</tbody>

This is arguably the most common mistake seen when iterating over an array in React. This approach isn't technically "wrong", it's just... "dangerous" if you don't know what you are doing. If you are iterating through a static array then this is a perfectly valid approach (e.g. an array of links in your navigation menu). However, if you are adding, removing, reordering or filtering items, then you need to be careful. Take a look at this detailed explanation in the official documentation.