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 ID | Repeated 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
Concept | Explanation |
---|---|
List Rendering | Use .map() to loop and render items in JSX |
Key Prop | Unique identifier to help React manage updates |
Best Key Choice | Prefer item.id over index |
Dynamic UI | Lists 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
Advertisement Slot 1
Advertisement Slot 2