C
React/Components/Lesson 06

Lists and Keys

25 min·theory
This chapter
4/4
JavaScript

Lists and Keys

💡 Why should you learn this?

🎯 This is the most fundamental way to display array data on screen.
💼 Using Key incorrectly causes bugs, so this is essential to learn.
It is required for every list: product listings, comments, search results, and more.
🏢 실무에서는
In real-world projects, you use `map()` to transform a product array received from a database into a list of product cards. If you do not set the Key correctly, a bug can occur where the wrong item disappears when you delete an item.

Lists and Keys — Converting arrays to UI with map

Real-world analogy: Class roster

Just like a teacher goes through a list of students and creates an attendance card for each one,
React uses map() to transform an array into a list of components.

Basic pattern

jsx
const fruits = ["Apple", "Banana", "Grape"];
return (
  <ul>
    {fruits.map((fruit, index) => (
      <li key={index}>{fruit}</li>
    ))}
  </ul>
);

Why are keys necessary?

Keys give each element a unique identifier so React can tell

which items have been added, removed, or changed in a list.

Recommended key priority

1. key={item.id} — unique ID from the server (best)

2. key={item.slug} — unique string

3. key={index} — index (only when the list never reorders)

What happens without keys?

  • Performance degradation (entire list re-renders)
  • Console warnings appear
  • Animations and state may malfunction
💻 Rendering a product list + correct key usage
// ===== Input: Product data array =====
const products = [
  { id: 1, name: "Laptop", price: 1200000, inStock: true },
  { id: 2, name: "Mouse", price: 45000, inStock: true },
  { id: 3, name: "Keyboard", price: 89000, inStock: false },
];

// ===== Processing: Transform array → components with map =====
function ProductList() {
  return (
    <ul>
      {products.map(product => (
        // Key must be a unique value; if an id exists, use id
        <ProductItem key={product.id} product={product} />
      ))}
    </ul>
  );
}

// ===== Individual Product Component =====
function ProductItem({ product }) {
  const { name, price, inStock } = product;  // Destructuring assignment

  // Output: Product card UI
  return (
    <li style={{ opacity: inStock ? 1 : 0.5 }}>
      <strong>{name}</strong>
      <span>{price.toLocaleString()} KRW</span>
      {/* Conditional rendering: Display stock status */}
      {inStock ? (
        <span style={{ color: "green" }}>In Stock</span>
      ) : (
        <span style={{ color: "red" }}>Sold Out</span>
      )}
    </li>
  );
}

💡 💡 Key Tips

  • DB ID: The ideal key
  • Index key: Only for static lists with no sorting or deletion
  • crypto.randomUUID(): Generate IDs on the client side
  • Performance: With correct keys, React updates only the minimum necessary DOM

This concept is fundamental to React component development. Understand React's declarative UI paradigm and clearly distinguish the difference between props and state. A component should behave like a pure function — always returning the same output (JSX) for the same input (props).

⚛️ React Pattern — Lists and Keys

Learn step by step, with code, how Lists and Keys are used in React.
1 🧩 1. Scenarios for using Lists and Keys
Situations where this feature is needed.
2 💻 2. Writing the code
Basic usage of Lists and Keys.
3 🎨 3. Rendering result
What the user sees on screen.
4 💡 4. Practical tips
Common pitfalls and best practices.

📋 List rendering + add/delete

Edit the code directly and changes are reflected automatically after 0.7 seconds. Runs instantly in the browser with React 18 + Babel.
🖥️ Result — rendered React component
✏️ React 코드 수정하기 (클릭해서 열기)
⚛️ React 18 + Babel Standalone — see the result first, then edit the code yourself.

Check your understanding

What happens if you don't use the key prop in list rendering?
💡 Without a key, React cannot tell which element changed when the list updates and re-renders the entire list. A console warning — 'Each child in a list should have a unique key prop' — will appear.
Read this first: Conditional Rendering
Up next: useState
Lists and key - React