Rendering dynamic lists of data is a core capability of React. Lists are generated using standard JavaScript array iteration methods like Array.prototype.map().
key PropEvery item in a rendered list requires a unique key prop. Keys provide a persistent identity to elements across re-renders, enabling React's reconciliation engine to determine which items were added, changed, or removed without re-rendering the entire list DOM.
flowchart TD
List["Data Array [id: 101, id: 102]"] --> Map["Array.prototype.map()"]
Map --> Child1["<ListItem key={101} />"]
Map --> Child2["<ListItem key={102} />"]
Child1 & Child2 --> DOM["Reconciled Browser DOM"]
import React, { useState } from 'react';
export default function TaskList() {
const [tasks, setTasks] = useState([
{ id: 't-1', text: 'Configure Webpack build pipeline', completed: true },
{ id: 't-2', text: 'Setup Redux Toolkit store', completed: false },
{ id: 't-3', text: 'Write end-to-end Cypress tests', completed: false },
]);
const toggleTask = (id) => {
setTasks(prevTasks =>
prevTasks.map(task =>
task.id === id ? { ...task, completed: !task.completed } : task
)
);
};
return (
<div className="task-container">
<h3>Project Task List ({tasks.length})</h3>
<ul>
{tasks.map((task) => (
<li
key={task.id}
className={task.completed ? 'completed' : 'pending'}
onClick={() => toggleTask(task.id)}
>
<span>{task.text}</span>
<button type="button">{task.completed ? 'Undo' : 'Done'}</button>
</li>
))}
</ul>
</div>
);
}
key={index} when list items can reorder, filter, or insert elements dynamically. Using indices as keys leads to state corruption in input fields and unexpected rendering bugs.Given an array of user objects [{ id: 'u1', name: 'Alice' }, { id: 'u2', name: 'Bob' }], render an HTML <ul> list where each <li> displays the user's name with a unique key derived from the user's id.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With