Keys in children components are important
The key is an attribute that you must pass to all components created dynamically from an array. It’s a unique and constant id that React uses to identify each component in the DOM and to know whether it’s a different component or the same one. Using keys ensures that the child component is preserved and not recreated and prevents weird things from happening.
Key is not really about performance, it’s more about identity (which in turn leads to better performance). Randomly assigned and changing values do not form an identity Paul O’Shannessy
- Use an existing unique value of the object.
- Define the keys in the parent components, not in child components
//bad
...
render() {
<div key={{item.key}}>{{item.name}}</div>
}
...
//good
<MyComponent key={{item.key}}/>
- Using array index is a bad practice.
random()
will not work
//bad
<MyComponent key={{Math.random()}}/>
- You can create your own unique id. Be sure that the method is fast and attach it to your object.
- When the number of children is large or contains expensive components, use keys to improve performance.
- You must provide the key attribute for all children of ReactCSSTransitionGroup.

Five years worth of JavaScript that you can learn in just a few weeks. This is the most complete and efficient flashcards ever created.
GET THE CARDS NOW
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW