const courses = ["HTML", "CSS", "JavaScript"];
function CourseList() {
return (
<ul>
{courses.map((course) => (
<li key={course}>{course}</li>
))}
</ul>
);
}The key prop isn't for styling or logic in your own code โ it's a hidden signal that tells React exactly which array item is which, across re-renders. Without stable keys, React can confuse one list item for another when items are added, removed, or reordered, causing subtle bugs like form inputs retaining the wrong value after a reorder.
// Risky if the list can be reordered, filtered, or items added/removed from the middle
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
// Better - use a stable, unique ID from your actual data
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}Using the array index as a key works fine for a static list that never changes order. But if items can be added, removed, or reordered, the index shifts even though the underlying item didn't โ always prefer a real, stable ID from your data (like a database ID) whenever one is available.
const products = [
{ id: 1, name: "Mouse", inStock: true },
{ id: 2, name: "Keyboard", inStock: false }
];
function AvailableProducts() {
return (
<ul>
{products
.filter((p) => p.inStock)
.map((p) => <li key={p.id}>{p.name}</li>)}
</ul>
);
}Chaining .filter() before .map() is the standard pattern for rendering only a subset of your data โ far cleaner than an if-check inside the loop.
Omitting key doesn't crash your app, but React logs a clear console warning ("Each child in a list should have a unique key prop") and may re-render the list less efficiently or incorrectly. Always add a key โ treat the warning as an error to fix immediately.
Given an array of task objects with id and text fields, render them as a list, then filter to show only tasks where completed is false.
const tasks = [
{ id: 1, text: "Learn JSX", completed: true },
{ id: 2, text: "Learn Props", completed: false },
{ id: 3, text: "Learn State", completed: false }
];
function TaskList() {
return (
<ul>
{tasks
.filter(t => !t.completed)
.map(t => <li key={t.id}>{t.text}</li>)}
</ul>
);
}
Q Can I use the same key twice in one list?
No โ keys must be unique among siblings in the same list. Duplicate keys cause React to behave unpredictably, potentially mixing up which DOM element belongs to which data item.
Q Do keys need to be globally unique across the whole app?
No, only unique among the siblings within that specific list. The same key value can safely be reused in a completely different list elsewhere in your app.