I know that we need a key to know which element from the list has been deleted or modified. But how does "key" exactly work? What happens "under the hood" in React if we miss a "key" attribute?
Asked
Active
Viewed 126 times
1 Answers
1
If keys are not added, React has to iterate over the entire list if you have inserted an element at the beginning. Since it doesn't know what else has changed. For example, converting between these two trees works poorly:
<ul>
<li>Duke</li>
<li>Villanova</li>
</ul>
<ul>
<li>Connecticut</li>
<li>Duke</li>
<li>Villanova</li>
</ul>
React will mutate every child instead of realizing it can keep the <li>Duke</li>
and <li>Villanova</li>
subtrees intact.
Note that if item is inserted at end, React optimizes this and O(n) comparisons may not be made.
There are other potential dangers of using indexes as keys. See why this is an anti-pattern

Ashutosh
- 1,000
- 15
- 39