React Interview Question: Avoiding Math.random() as a Key

⚛️ Top 150 React Interview Questions – 125/150 📌 Topic: Why is key={Math.random()} Bad? ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Using Math.random() as a key generates a new identity on every render. React uses the key to track elements between renders. If the key keeps changing, React assumes: 👉 “This is a completely new component.” So instead of updating the element, React destroys it and creates a new one. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY is it bad? 🚨 Performance Degradation React cannot efficiently diff elements. It unmounts and remounts everything. 💥 Loss of Component State All local state (useState) is lost. Examples: • Input values reset • Scroll position disappears • Checkbox states vanish 🎯 UX Glitches • Cursor jumps out of input fields • Animations break • Focus disappears You basically break React’s reconciliation system. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW to fix it? ❌ BAD (Unstable Key) {items.map(item => ( <input key={Math.random()} /> ))} Key changes every render → React remounts everything. ✅ GOOD (Stable Key) {items.map(item => ( <input key={item.id} /> ))} Use a unique, stable identifier like: • Database ID • UUID (stored once) • Unique slug React can now track elements correctly. ⚠️ Rule: Keys must be: • Stable • Unique • Predictable Never generated during render. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE does this matter most? ⌨️ Input Fields Prevents cursor from jumping while typing. 📜 Large Lists Avoids re-rendering hundreds of elements unnecessarily. 🧠 Stateful Components Preserves internal useState data. 🎬 Animated Lists Prevents broken transitions. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY (Easy to Remember) Think of a Library Card 📚 If your library card number changed every time you entered the building, the librarian (React) would think you are a new person every visit. They would delete your old record and create a new one from scratch. Stable key = Stable identity. Random key = Identity crisis. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactKeys #FrontendDevelopment #Performance #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories