Reputation: 31
If keys should be referenced instead of the index when searching through an array, why is there such a loose format for keys? I feel like it would make referencing keys a lot easier if they were auto generated like how MongoDB auto generates an object id for a document regardless of what _id has been set as. Was this feature too expensive to implement or not thought of by Facebook? Just wondering because lately I have been getting errors saying I should be referencing by the key, yet my code would work as intended. I don’t fully understand why a key is so much better to reference by if it can be in any unique format. If someone can school on me why this is the way it is, I’d very much appreciate it. Thank you.
Upvotes: 3
Views: 192
Reputation: 4333
keys
help React to know if a content needs re-rendering or not. Let us say you have an array of five objects and you are mapping over them. You deleted the fourth element and now the fifth element moved into the position of the fourth element in the array. Now for React if there were dynamic keys which React is generating on its own, it wouldn't know that it was the fifth element that slid into the fourth elements place. So it has to delete the node and create a new node. But if it was given a key by you, it will see that the key of the fourth element is the key that belonged to the fifth element and doesn't need to delete the node.
The case you said is similar to using index as keys while mapping over the array. You can read this article to know why you shouldn't use an index as keys.
Upvotes: 1