Lists & Keys Cheat Sheet
Subject: React
🧩 Lists & Keys Cheat Sheet
🧩 Concept | ✅ Syntax / Example | 💡 Description / Use Case |
---|---|---|
Render List with map() | {items.map(item => <li>{item}</li>)} | Loop through an array to display a list in JSX |
Add key Prop | <li key={item.id}>{item.name}</li> | Key helps React track elements efficiently |
Best Key Practice | Use a unique ID, not index: key={user.id} | Avoid bugs during reordering and re-renders |
Bad Key Example | key={index} | Only safe for static, never-changing lists |
Render Custom Component | {users.map(u => <UserCard key={u.id} name={u.name} />)} | Render components for each item in a list |
Delete from List | setList(list.filter((_, i) => i !== index)) | Remove an item from state array |
Update Item in List | setList(list.map((item, i) => i === id ? newItem : item)) | Replace an item while preserving others |
Add Item to List | setList([...list, newItem]) | Add an item to the end of an array |
Keys with Objects | {products.map(p => <li key={p.id}>{p.name}</li>)} | Always prefer object .id if available |
Avoid Duplicate Keys | Don’t use same key for multiple elements | Causes UI bugs and performance issues |
Advertisement Slot 1
Advertisement Slot 2