Chapter 8: Rendering Lists & Keys

We’ll go through everything step by step, like I’m sitting next to you in Mumbai showing you live examples.

1. Why We Use .map() to Render Lists

In React, you cannot just write a JavaScript for loop inside JSX — because JSX expects expressions, not statements.

The cleanest and most common way to render a list is:

tsx

Why .map()?

  • It creates a new array of JSX elements
  • React can efficiently render/update/remove DOM elements
  • It’s declarative (you describe what to show, React handles how)

2. Basic Example: Simple List of Names

Create src/components/NameList.tsx

tsx

Use in App.tsx:

tsx

3. The Huge Importance of key Prop

React uses the key prop to uniquely identify each list item. Without proper keys, React cannot efficiently figure out which items changed, which were added, or which were removed.

What happens if you forget keys or use bad keys?

Wrong key usage Problem
No key at all React warning in console: “Each child in a list should have a unique ‘key’ prop”
Use index as key (key={index}) Major bugs when list changes (items reorder, animations break, state lost)
Duplicate keys React gets confused, re-renders wrong items, performance drops

Golden Rule (2026 best practice): Every list item must have a unique, stable key Best options (in order of preference):

  1. Unique ID from your data (database id, uuid) → best
  2. Unique natural property (username, email, product code)
  3. Only as last resort → index (but only if list never reorders/adds/removes in middle)

4. Dynamic Lists with Proper Unique Keys

Let’s build a realistic Todo List with add/remove functionality.

Create src/components/TodoList.tsx

tsx

5. Why key={index} is Dangerous (Quick Demo)

If you ever use key={index} in a list that reorders or items are added/removed in the middle, React will get confused:

  • Checkboxes might stay checked on wrong items
  • Animations break
  • Input focus jumps to wrong field
  • State gets lost

Always use a stable, unique identifier from your data whenever possible.

Summary – Chapter 8 Key Takeaways

  • Use .map() to turn arrays into JSX lists
  • Every list item needs a unique key prop
  • Best key → unique ID from your data (database id, uuid, etc.)
  • Never use key={index} unless the list is static (never changes order)
  • Combine with conditional rendering for empty states
  • React uses keys to efficiently update the DOM

Mini Homework

  1. Create a ProductGrid component
  2. Have an array of products (at least 5) with: id, name, price, imageUrl
  3. Render them in a beautiful grid (use flex/grid)
  4. Each product card should have key={product.id}
  5. Bonus: Add a “Sort by price” button that re-sorts the list

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *