Keys and Why We Need Them…
Why Do We Need Keys?
We all have been given fair warning that “a key problem is a me problem,” so hopefully this will clear any confusion up.
Say we have this code:
We get an error message:
“Warning: Each child in a list should have a unique ‘key’ prop.%s%s See https://fb.me/react-warning-keys for more information.%s”
This error message isn’t really the issue. It can be easily fixed by giving each of these list items a unique id.
Now, in this case, our unique IDs are actually just the indices which are not truly unique. It is important to give our keys unique IDs because of this reason…
If a new number comes along and inserts itself into the array, React isn’t going to know what’s going on. By default, when React looks at the children of a DOM node, it iterates over both lists at the same time and generates a mutation whenever there’s a difference.
When React tries to match the two arrays, all of the li elements after 6 are going to look different and they will be remade. Let’s take a closer look:
Component instances are updated and reused based on their key. If the key is an index, moving an item changes it.
React will mutate every child instead of realizing it can keep the <li>3</li>, <li>4</li>, <li>5</li> subtrees intact. This efficiency can be a problem. Unstable keys can cause component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components. Whenever possible it is important to make sure to use real unique keys. Most of the time you will be able to use the unique ID from your data but in the case that isn’t an option, you can add a new ID property to your model or hash some parts of the content to generate a key. It’s also good to note that keys only have to be unique among its siblings and they do not need to be globally unique.
To recap:
-always use a key
-always use a unique key
-only use index as keys if your list items are static. They don’t have IDs you can use as a key, and the list will not be reordered or filtered
SO basically just always use a unique key always, please, thanks.