Stop 08 · React FundamentalsTopics · 8/10

Lists and Keys

Part of the MERN Stack Roadmap

In short

Products, notes, comments and orders all come back from your API as arrays. Turning an array into a list of components is one of the things you will do most in React, and keys make sure it updates correctly.

You render arrays with map, and each item needs a stable, unique key prop, usually the MongoDB _id, so React can update the right element.

The jaadu stands beside an airport baggage belt, tying bright name tags onto a row of identical black suitcases as they roll past.

Think of it like this

Name tags on luggage

At the airport belt, hundreds of black suitcases look the same. You find yours by its tag, not by its position on the belt, because positions keep changing. React's key is that tag. With a stable key like the note's _id, React knows exactly which item moved, changed or left.

Watch it happen

Deleting the first note: index keys vs _id keys

Buy milk
0
Call Ravi
1
Pay rent
2

1/5Three notes rendered from an array. Each has an editable input next to it.

The big ideas

What you need to know

map turns data into JSX

notes.map(note => <NoteCard key={note._id} note={note} />) creates one component per item.

Keys must be stable and unique

Use the MongoDB _id or another real id. Keys only need to be unique among siblings, not the whole app.

Avoid index as key

Index keys break when items are added, removed or reordered. They are only safe for static lists that never change.

filter and sort first

Do notes.filter(...).map(...) to show a subset. Copy before sorting: [...notes].sort(...), because sort changes the original array.

See it in code

Walk through the code

jsx
1import { useState } from "react";2 3const initialProducts = [4  { _id: "p1", name: "Cotton Kurta", price: 899, inStock: true },5  { _id: "p2", name: "Steel Bottle", price: 349, inStock: false },6  { _id: "p3", name: "Laptop Bag", price: 1299, inStock: true },7];8 9export default function ProductList() {10  const [products, setProducts] = useState(initialProducts);11  const [onlyInStock, setOnlyInStock] = useState(false);12 13  const visible = onlyInStock ? products.filter((p) => p.inStock) : products;14 15  function remove(id) {16    setProducts((prev) => prev.filter((p) => p._id !== id));17  }18 19  return (20    <>21      <label>22        <input type="checkbox" checked={onlyInStock} onChange={(e) => setOnlyInStock(e.target.checked)} />23        In stock only24      </label>25      <ul>26        {visible.map((p) => (27          <li key={p._id}>28            {p.name} - ₹{p.price}29            <button onClick={() => remove(p._id)}>Remove</button>30          </li>31        ))}32      </ul>33    </>34  );35}

1/4Data shaped like what Mongoose returns: every item has an _id.

Filter, render and remove items, always keyed by _id.

Save yourself the pain

Common mistakes

Oops

Using key={Math.random()} to silence the warning.

Do this instead

A new random key on every render makes React destroy and recreate every item. Use the real _id.

Oops

Putting the key on an inner element instead of the outermost one returned by map.

Do this instead

The key goes on the element map returns directly, such as the li or the NoteCard.

Oops

Calling products.sort() directly on state.

Do this instead

Sort a copy: [...products].sort((a, b) => a.price - b.price). Mutating state skips re-renders and causes bugs.

Your mission

A sortable contact list

~25 min

Quick check

Which is the best key for a list of notes loaded from MongoDB?

Go deeper

  1. 1Render a list of products from an array using map and product._id as the key.
  2. 2Avoid using the array index as a key when items can be added or removed.
  3. 3Combine filter and map to show only items that match a search box.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge