SkillPilotAI

Lists and keys

Lists in React are built by mapping an array to elements, and every element needs a key: a stable identity React uses to match old and new items between renders. A wrong key (index or random) leads to typed values jumping to the wrong item or the whole list being rebuilt.

29.1 Array to list with map

  • products.map returns an <li> for every product; React renders the array of elements directly.
  • All three phones appear, but the console warns: Each child in a list should have a unique "key" prop.
React (JSX)
const products = [  { id: "p1", name: "iPhone 16" },  { id: "p2", name: "Pixel 9" },  { id: "p3", name: "OnePlus 13" },]; function ProductList() {  return (    <ul>      {products.map((p) => (        <li>{p.name}</li>      ))}    </ul>  );}
Output
iPhone 16Pixel 9OnePlus 13Console: Each child in a list should have a unique "key" prop.

29.2 Why React needs a key

  • On a state change React compares the new list with the old one and updates only what changed in the DOM (reconciliation).
  • Without a key, items are matched by position: first with first, second with second.
  • A key is a permanent identity, like a roll number in class, so React finds the right item even when the order changes.
How React matches list items
  1. 1.State changes: a new list is rendered

  2. 2.React compares the old list with the new list

  3. 3.Match items by key (or by position if there is no key)

  4. 4.Same key: reuse and move the element; new key: create; missing key: remove

29.3 Fix: the key prop

  • Give the element returned directly inside map a key prop: key={p.id}.
  • The id is unique per product, so the warning goes away and the screen looks the same.
React (JSX)
function ProductList() {  return (    <ul>      {products.map((p) => (        <li key={p.id}>{p.name}</li>      ))}    </ul>  );}
Output
iPhone 16Pixel 9OnePlus 13

29.4 Bug: index as key

  • Todos keeps the list in state; Add puts Bread at the top; key={index}.
  • Type "2 litre" next to Milk, click Add: "2 litre" now shows next to Bread.
React (JSX)
import { useState } from "react";import { groceries } from "./data";function Todos() {  const [list, setList] = useState(groceries);  const addOnTop = () => setList([    { id: crypto.randomUUID(), name: "Bread" },    ...list,  ]);  return <div>    <button onClick={addOnTop}>Add</button>    {list.map((item, index) => (      <p key={index}>{item.name} <input /></p>    ))}  </div>;}
Output
-- start --[button] AddMilk [ ______ ]Eggs [ ______ ]-- type "2 litre" next to Milk --[button] AddMilk [ 2 litre ]Eggs [ ______ ]-- click Add --[button] AddBread [ 2 litre ]Milk [ ______ ]Eggs [ ______ ]
What goes wrong with an index key
  1. 1.Before: key 0 = Milk (input has "2 litre"), key 1 = Eggs

  2. 2.Bread is added on top and now gets key 0

  3. 3.React sees key 0 already exists and reuses that <p> and its <input>

  4. 4.Only the text changes from Milk to Bread

  5. 5.The typed value lives in the DOM input, so "2 litre" sticks to Bread

29.5 Fix: a stable id as key

  • Use item.id: the id travels with the data.
  • Every grocery already has an id; crypto.randomUUID() gives the new Bread its own id when it is created.
  • Now the Milk element moves with Milk; Bread's input starts empty.
React (JSX)
    {list.map((item) => (      <p key={item.id}>{item.name} <input /></p>    ))}
Output
-- "2 litre" typed next to Milk --[button] AddMilk [ 2 litre ]Eggs [ ______ ]-- click Add --[button] AddBread [ ______ ]Milk [ 2 litre ]Eggs [ ______ ]

Checkpoint: key={Math.random()} gives every item a new key on every render, so React treats all items as new, destroys and rebuilds every element, and all typed input is lost (and it is slow).

React (JSX)
    {list.map((item) => (      <p key={Math.random()}>{item.name} <input /></p>    ))}
Output
-- "2 litre" typed next to Milk --[button] AddMilk [ 2 litre ]Eggs [ ______ ]-- click Add --[button] AddBread [ ______ ]Milk [ ______ ]Eggs [ ______ ]
Key choiceStable?Result when adding on top / reordering
Database / API idYesCorrect: elements move with their data
crypto.randomUUID() at creationYesCorrect (id is created once with the data)
Array indexNo, changes with positionTyped values / state stick to the wrong item
Math.random() or Date.now() in renderNo, new every renderEverything is rebuilt, input is lost, slow

29.6 Common mistakes

  • Putting the key inside the child component (on its <li>) instead of on the element map returns: the warning still appears.
  • Expecting to read key from props: key is not a normal prop; pass the id separately if the child needs it.
  • Generating keys during render with Math.random() or Date.now().
  • Myth: index keys are always wrong. For a static list that never reorders or filters (like footer links) an index is safe; the problem is when order or position can change.
React (JSX)
// Wrong: key inside the child, warning still appearsfunction ProductCard({ product }) {  return <li key={product.id}>{product.name}</li>;} function ProductList({ products }) {  return (    <ul>      {products.map((p) => (        <ProductCard product={p} />      ))}    </ul>  );}
React (JSX)
// Right: key on the element map returnsfunction ProductCard({ product }) {  return <li>{product.name}</li>;} function ProductList({ products }) {  return (    <ul>      {products.map((p) => (        <ProductCard key={p.id} product={p} />      ))}    </ul>  );}

29.7 Four rules of keys

  1. Unique among siblings (not across the whole app).
  2. Stable: never random in render; assign the id when the data is created.
  3. Best key: an id from your database or API.
  4. Always on the direct element inside map.

29.8 Interview tips

  • A key gives every list item a stable identity.
  • On re-render React compares old and new lists by key to reuse, move or remove the right element.
  • Without keys React matches by position.
  • Give the index-key bug as an example: adding on top makes typed input stick to the wrong item.
  • Index is acceptable only for static lists; random keys force a full rebuild.