Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  117] [ 5]  / answers: 1 / hits: 23422  / 7 Years ago, wed, march 15, 2017, 12:00:00

I want to understand what happens if I don't use keys in dynamically added components. I removed keys and it renders without any issue and just gave warning messages regarding key usage. Would someone please give some example of what the consequences are if we don't use keys?


More From » reactjs

 Answers
11

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:



Example:



const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);


TL;DR Use unique and constant keys when rendering dynamic children, or expect strange things to happen.




One of the tricky aspects I've found during the few weeks I've been using React.js is to understand the key property you're expected to pass to a component when it's part of an array of children. It's not that you have to specify this property, things will work most of the time apart from getting this warning on the console:



Each child in an array should have a unique key prop. Check the render method of undefined.
By reading the linked documentation it can be easy to not see the implications of this affirmation:



When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
At first it looked to me it was all about performance but, as Paul O’Shannessy pointed, it's actually about identity.



The key here is to understand not everything in the DOM has a representation in React Virtual DOM and, because direct manipulations of the DOM (like a user changing an value or a jQuery plugin listening an element) are unnoticed by React, not using unique and constant keys will end up with React recreating the DOM node of a component when the key is not constant (and losing any untracked state in the node) or reusing a DOM node to render another component when the key is not unique (and tying its state to this other component).



Here you have a live demo showing how awful the results are:



http://jsfiddle.net/frosas/S4Dju/



Just add an item, change it, add more items and see what happens.




Also see



Source


[#58546] Monday, March 13, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristinadomoniquel

Total Points: 320
Total Questions: 94
Total Answers: 94

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
cristinadomoniquel questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Mon, Aug 17, 20, 00:00, 4 Years ago
;