Lists and Keys

Subject: React

πŸ” What is a List in React?

In React, a list refers to an array of data rendered dynamically using JSX.

React commonly uses JavaScript’s .map() method to display lists.


🧠 Why Render Lists?

  • Display items from data (users, products, tutorials)
  • Render reusable UI blocks from arrays
  • Keep UI synced with data (tables, menus)

βœ… Basic Example: Rendering an Array

πŸ” Output:


⚠️ Why You Need a key Prop

Every element in a rendered list must include a key prop:

βœ… Reason:

  • Helps React identify which items changed
  • Enables efficient DOM updates
  • Avoids rendering bugs in reordering

πŸ”‘ Best Practices for Keys

βœ… Good Key❌ Bad Key
item.id (unique)index (only if static)
uuid or DB IDRepeated strings like "1"

If the order of items changes, using indexes can cause bugs in React rendering.


πŸ§ͺ Realistic Example: Rendering Users


🧰 Rendering Components from a List


πŸ“₯ Example: Deleting List Items


πŸ” Updating a List Using State


🧠 Summary

ConceptExplanation
List RenderingUse .map() to loop and render items in JSX
Key PropUnique identifier to help React manage updates
Best Key ChoicePrefer item.id over index
Dynamic UILists enable dynamic and interactive UIs

πŸ”š Final Thoughts

  • Lists and Keys are essential for repeatable, dynamic UIs
  • React won't warn if keys are missing, but performance suffers
  • Modularize: use components inside .map() for clean structure

πŸ‘‰ Check the Lists and Keys Cheat Sheet