🎯 React Lists, Keys & Conditional Rendering

Day 14-16: Interactive Learning Guide

📋 Lists aur Dynamic Rendering

React mein hum arrays ko UI elements mein convert karte hain. Jab bhi aapko multiple similar items dikhane hain (like products, users, posts), tab aap lists use karte hain.

🔍 Map vs forEach in Rendering

✅ map() - CORRECT

Returns naya array

JSX elements return karta hai

Rendering ke liye perfect

❌ forEach() - WRONG

Returns undefined

Kuch return nahi karta

Rendering ke liye use nahi hota

// ✅ Correct Way - map() use karo const items = ['Apple', 'Banana', 'Orange']; return ( <ul> {items.map(item => ( <li key={item}>{item}</li> ))} </ul> ); // ❌ Wrong Way - forEach() kuch return nahi karta items.forEach(item => ( <li>{item}</li> // Ye render nahi hoga! ));

🎮 Interactive Demo: List Rendering

🔑 Keys: React ki Identity System

Keys React ko batate hain ki kaunsa element kaunsa hai. Ye ek unique identifier hai jo React ko help karta hai efficiently re-render karne mein.

Why Keys Matter?

Without Keys: React ko pata nahi chalta ki list mein kya change hua, toh wo puri list ko re-render kar deta hai.

With Keys: React sirf changed elements ko hi update karta hai, making it super fast! 🚀

⚠️ Index as Key - Common Mistake

🎮 Demo: Index as Key Problem

Niche waale buttons se dekho ki index as key kyun problem create karta hai:

// ❌ WRONG - Index as key (avoid this!) items.map((item, index) => ( <li key={index}>{item}</li> )); // ✅ CORRECT - Unique ID as key items.map(item => ( <li key={item.id}>{item.name}</li> )); // ⚠️ OK - Last resort (jab item unique aur stable ho) items.map(item => ( <li key={item}>{item}</li> ));

❌ Index as Key Problem

Jab list reorder hoti hai:

  • Keys change ho jati hain
  • React confused ho jata hai
  • Wrong elements update hote hain
  • State mess ho jata hai

✅ Unique Key Benefits

Stable keys ke saath:

  • Keys same rehti hain
  • React correctly track karta hai
  • Sahi elements update hote hain
  • Performance optimal rehti hai

⚠️ Common Mistakes aur Best Practices

🐛 Mistake #1: Missing Keys

Problem: Keys na dena React ko warning deta hai aur performance issues create karta hai.

// ❌ Wrong - No key provided {items.map(item => <li>{item}</li>)} // ✅ Correct - Key provided {items.map(item => <li key={item.id}>{item}</li>)}

🐛 Mistake #2: Non-Unique Keys

Problem: Same key multiple elements ko dena React ko confuse kar deta hai.

// ❌ Wrong - Duplicate keys {items.map(item => <li key="item">{item}</li>)} // ✅ Correct - Unique keys {items.map(item => <li key={item.id}>{item}</li>)}

🐛 Mistake #3: 0 in Conditional Rendering

Problem: Agar count 0 hai, toh count && <div>{count}</div> screen pe "0" display karega!

// ❌ Wrong - Will render "0" on screen {count && <div>Items: {count}</div>} // ✅ Correct - Explicit boolean check {count > 0 && <div>Items: {count}</div>} {Boolean(count) && <div>Items: {count}</div>}

🎮 Demo: The "0" Problem

Item count ko 0 karo aur dekho kya hota hai:

✅ Best Practices Summary

✅ DO THIS

  • Unique, stable IDs use karo
  • Database IDs prefer karo
  • Explicit boolean checks
  • Keys ko props mein pass mat karo
  • Early returns for readability

❌ DON'T DO THIS

  • Index as key (unless static list)
  • Random values as keys
  • Missing keys
  • Duplicate keys
  • Math.random() as key

🎭 Conditional Rendering Patterns

React mein hum conditions ke basis par different UI render karte hain. Iske multiple tarike hain!

1️⃣ If/Else Statement

function Greeting({ isLoggedIn }) { if (isLoggedIn) { return <h1>Welcome back!</h1>; } else { return <h1>Please sign in.</h1>; } }

2️⃣ Ternary Operator (? :)

return ( <div> {isLoggedIn ? ( <h1>Welcome back!</h1> ) : ( <h1>Please sign in.</h1> )} </div> );

3️⃣ Logical && (Short-circuiting)

return ( <div> {isLoggedIn && <h1>Welcome back!</h1>} {messages.length > 0 && ( <p>You have {messages.length} messages</p> )} </div> );

4️⃣ Early Return

function UserProfile({ user }) { if (!user) { return <p>Loading...</p>; } if (user.banned) { return <p>Account suspended</p>; } return <div>{user.name}</div>; }

🎮 Interactive Demo: Conditional Rendering Patterns

Login Status

Logged Out

Messages

0 messages

Premium User

Free Plan

💼 Interview Questions

Q1 Easy

React mein list rendering ke liye map() aur forEach() mein kya difference hai?

Answer: map() ek naya array return karta hai jo JSX elements contain karta hai, isliye wo rendering ke liye perfect hai. forEach() undefined return karta hai aur sirf side-effects ke liye use hota hai, rendering ke liye nahi.

Q2 Easy

Keys ka React mein kya role hai aur ye kyun important hain?

Answer: Keys React ko help karti hain identify karne mein ki kaunse items change, add ya remove hue hain. Ye React ko efficient re-rendering mein help karta hai by tracking which elements need to be updated. Keys unique aur stable honi chahiye.

Q3 Medium

Index ko key ke taur par use karna kyun problematic hai?

Answer: Jab list reorder, filter ya modify hoti hai, toh index change ho jati hai. Isse React wrong elements ko update kar sakta hai aur component state mess ho sakta hai. Example: agar aap first item delete karte ho, toh sab indices shift ho jati hain, aur React confused ho jata hai ki kaunsa element actually delete hua.

Q4 Medium

Conditional rendering ke different patterns kaunse hain aur kab kaunsa use karna chahiye?

Answer:
• if/else: Jab complex logic ho ya multiple conditions check karni ho
• Ternary (? :): Simple two-way conditions ke liye (if-else alternative)
• Logical && : Jab sirf true case mein kuch render karna ho
• Early return: Multiple validation checks ke liye, code readability improve karta hai

Q5 Medium

{isLoggedIn && <Dashboard />} mein agar isLoggedIn false hai toh kya render hoga?

Answer: Kuch bhi render nahi hoga. Logical && operator short-circuit evaluation use karta hai. Agar left side (isLoggedIn) false hai, toh right side evaluate hi nahi hoga aur React false/null/undefined ko render nahi karta. However, agar 0 ya empty string ho, toh wo render ho jayega - ye common pitfall hai!

Q6 Hard

Agar aapke paas dynamic list hai jismein unique ID nahi hai, toh aap keys kaise handle karenge?

Answer: Best approach hai ek unique ID generate karna (using libraries like uuid ya crypto.randomUUID()). Agar items stable aur unique hain, toh content ko key bana sakte ho. Last resort mein index use kar sakte ho, but sirf tab jab list static ho (no reordering, filtering, or adding/removing items). Production mein database se data aata hai jo already unique IDs have karta hai.

Q7 Hard

Explain the reconciliation algorithm aur keys ka isme kya role hai?

Answer: React ka reconciliation algorithm (also called "diffing") determine karta hai ki virtual DOM mein kya change hua hai. Keys isme critical role play karti hain:
• Without keys: React element type aur position se match karta hai, which is inefficient for lists
• With keys: React keys use karke elements ko uniquely identify kar pata hai across renders
• Agar key same hai toh React element ko reuse karta hai instead of destroying and recreating
• Ye performance ko dramatically improve karta hai especially large lists mein