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 PracticeUse a unique ID, not index: key={user.id}Avoid bugs during reordering and re-renders
Bad Key Examplekey={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 ListsetList(list.filter((_, i) => i !== index))Remove an item from state array
Update Item in ListsetList(list.map((item, i) => i === id ? newItem : item))Replace an item while preserving others
Add Item to ListsetList([...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 KeysDon’t use same key for multiple elementsCauses UI bugs and performance issues