Keys, and Why Index Is Usually Wrong
What a key is. A stable identity for each item, so React can tell which one moved rather than assuming position means identity.
Without keys, React compares by position. Item three is item three. That is fine until the list reorders, filters, or loses an entry near the top.
What goes wrong with an index key. Delete the first row of a list of inputs. Every row shifts up one position, but the keys are still 0, 1, 2. React concludes that nothing moved and only the last row disappeared, so it leaves the DOM nodes where they are. The typed values stay behind on the wrong rows.
The data is correct. The screen is wrong. That combination is very hard to debug, which is why the rule is worth taking seriously before you hit it.
Keys are for React, not for you. You cannot read a key inside the component. If the child needs the id, pass it as a separate prop as well.
The key only has to be unique among its siblings, not globally.
Mark this lesson complete
Signed in, your progress follows you to every device.