
ReactJS
Creating unique keys is essential for React list rendering.
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}import { v4 as uuidv4 } from "uuid";
function NoteList() {
const [notes, setNotes] = React.useState([]);
const addNote = () => {
setNotes([...notes, { id: uuidv4(), text: "" }]);
};
return (
<div>
{notes.map(note => (
<input key={note.id} defaultValue={note.text} />
))}
<button onClick={addNote}>Add Note</button>
</div>
);
}function CommentList({ userId, comments }) {
return (
<ul>
{comments.map(comment => (
<li key={\`{userId}-{comment.timestamp}\`}>
{comment.text}
</li>
))}
</ul>
);
}// ❌ Bad: Index changes when items reorder
{items.map((item, i) => <li key={i}>{item.text}</li>)}
// ✅ Good: Stable ID
{items.map(item => <li key={item.id}>{item.text}</li>)}| Property | Importance |
|---|---|
| Unique | No duplicates in list |
| Stable | Same data = same key across renders |
| Consistent | Doesn't change between renders |
function validateKeys(items) {
const keys = items.map(item => item.id);
return new Set(keys).size === keys.length; // True if unique
}
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
console.log(validateKeys(users)); // trueResources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward