Reputation: 1
{this.props.results.map(video => {
return (
<SearchVideoMeta
key={video.id}
id={video.id}
thumbnail={video.thumbnail}
title={video.title}
description={video.description}
/>
);
})}
Have a look at the above code snippet. Once SearchVideoMeta components are rendered, if the results state is updated, then SearchVideoMeta components are unmounted and mounted and mounted again with new results state. However if the key attribute(which is a unique key) is removed and results state is updated, then SearchVideoMeta components are updated with new results state(without unmounting and mounting again). I am wondering which way is more performant. React docs says it's always better to add key.
P.S: I am new to react and tried finding this in react documentation but of no help.
Upvotes: 0
Views: 1362
Reputation: 6253
It's certainly better to add your own key, and to also make sure that the key is not an index, but rather something unique like an ID.
Let's imagine you have you have a large list of people, and you are rendering this list in a ul and each person has their own li. Now you are using the index as the key for each li. When you delete the first person in the list for example, everything in the list will get shifted up one, and as a result the keys will change even tho the actual data has not, except of course for the one item which you have deleted. This in turn will cause all the unchanged lis to re render even tho they are exactly the same.
On the other hand, if you use an ID as the key, then no matter which item in the list you would delete, react will still know which item is the same and which is not, and as a result only re render what needs to be re rendered.
When you don't supply a key at all, react will use the index as a key for you which means you can potentially run in to this very bottleneck we just discussed.
As for the question of unmounting, I can't say definitely how expensive an unmount and re-mount is, but as an educated guess, it would be more efficient to only unmount and remount what actually changed vs re rendering the entire list including items which have not changed at all.
For a little more clarity on the subject, I would strongly urge you to check this video out.
Upvotes: 3