Consider the difference between these:
function NameList({names}) {
return (<ul>{names.map((name, index) =>
<li key={index}>{name}</li>
)}</ul>);
}
Given these names
<NameList names={['Bob', 'Charles']} />
It would render
<ul>
<li key="0"><Bob/li>
<li key="1"><Charles/li>
</ul>
If it re-renders with the names
<NameList names={['Alfred', 'Bob', 'Charles']} />
It would cause the following changes:
<ul>
- <li key="0"><Bob/li>
- <li key="1"><Charles/li>
+ <li key="0">Alfred</li>
+ <li key="1">Bob</li>
+ <li key="2"><Charles/li>
</ul>
Since the index key
wasn't stable, as far as React is concerned, the two first <li>
have changed, and a third one was added.
However, if you use name
as the key
function NameList({names}) {
return (<ul>{names.map((name, index) =>
- <li key={index}>{name}</li>
+ <li key={name}>{name}</li>
)}</ul>);
}
The same scenario would result in a much smaller change:
<ul>
+ <li key="Alfred">Alfred</li>
<li key="Bob"><Bob/li>
<li key="Charles"><Charles/li>
</ul>
Here, React can figure out that the two original <li>
haven't changed, but a third one was prepended, so it just adds that.