Lists & Keys

How to render arrays of data into components, and why React demands a unique key for each item.

React3 min readConcept 12 of 46

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!

const [items, setItems] = useState([
{ id: 'a', name: 'Apple' },
{ id: 'b', name: 'Banana' },
{ id: 'c', name: 'Cherry' }
]);
 
return (
    {items.map((item, index) => (
    // ❌ BUG: Using index as key!
    // If the array is reordered, React will mix
    // up the elements and their internal state.
  • key={index}>
  • {item.name}
    ))}
    );
    • 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.

    1. 1Which JavaScript array method is heavily used in React to render lists?
    2. 2Why does React require a `key` prop when rendering lists?
    3. 3Why is it dangerous to use the array `index` as a key (e.g. `key={index}`) if the list can be reordered?

    Remember this

    • Use Array.map() to render lists of elements.
    • Every element immediately returned by .map() requires a unique key prop.
    • The key should ideally be a unique ID from your data (like a database ID).
    • Do not use the array index as 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.