Lists & Keys
How to render arrays of data into components, and why React demands a unique key for each item.
What it is
To render a list of items, you use the standard JavaScript Array.map() function to transform an array of data into an array of JSX elements.
React requires you to provide a special key prop to the outermost element returned by the .map() function. This key must be a unique string or number that uniquely identifies that item among its siblings.
Why keys matter
When a list changes (items are added, removed, or reordered), React needs to figure out exactly what changed so it can update the DOM efficiently.
Without keys, React doesn't know if an item was deleted or just moved. It assumes the array order represents the items' identities. Keys give React a stable identity for each element across renders.
How to do it
If you have an array const users = [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}].
You render it like this: users.map(user => <Profile key={user.id} name={user.name} />). Always use a unique database ID if you have one.
The Index Bug
Type something into the first item's input, then shuffle the list. Notice how the input text stays locked to the position (the index) rather than following the item it belongs to!
- Appleindex: 0
- Bananaindex: 1
- Cherryindex: 2
Type some text into the Apple input, then hit Shuffle. The text stays in the same position instead of following the Apple! This is because React used the array index as the identity.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Use
Array.map()to render lists of elements. - Every element immediately returned by
.map()requires a uniquekeyprop. - The key should ideally be a unique ID from your data (like a database ID).
- Do not use the array
indexas a key if the list can ever be sorted, filtered, or reordered.
Done with this concept?
Mark it complete to track your progress. No login needed.