React js Keys Practice Questions with Solutions

Introduction

React mein Keys ka use list render karte waqt individual items ko uniquely identify karne ke liye hota hai. Jab list mein items add, remove ya reorder hote hain, keys React ko identify karne mein help karti hain ki kaunsa item change hua hai. Usually database ID ya koi stable unique value key ke liye use ki jati hai. Is chapter mein hum keys ke practical examples, common mistakes aur index ko key ke roop mein use karne ke issues solve karenge. React js Keys Practice questions with solutions help to understand the concepts.


1. What are Keys in React?

Answer:

Keys special values hoti hain jo React ko list ke individual items ko identify karne mein help karti hain.

Example:

function App() {
  const names = ["Rahul", "Priya", "Aman"];

  return (
    <div>
      {names.map((name) => (
        <p key={name}>{name}</p>
      ))}
    </div>
  );
}

export default App;

Yahan:

key={name}

har list item ko identify karne ke liye use ho raha hai.

Keys especially important hoti hain jab list update hoti hai.


2. Why are Keys important in React?

Answer:

React ko list ke items ke beech changes identify karne ke liye keys help karti hain.

Suppose list hai:

Apple
Banana
Mango

Aur baad mein ek new item add ho gaya:

Apple
Orange
Banana
Mango

Stable keys React ko batati hain ki existing items kaun se hain aur kaunsa new item add hua hai.

Isse React list updates ko efficiently handle kar sakta hai.


3. How do you add a key when rendering a list?

Answer:

List render karte waqt JSX element ko key prop de sakte hain.

Example:

function App() {
  const courses = ["React", "Node.js", "Python"];

  return (
    <ul>
      {courses.map((course) => (
        <li key={course}>
          {course}
        </li>
      ))}
    </ul>
  );
}

export default App;

Yahan:

key={course}

har <li> ko identify karne ke liye key provide karta hai.

Agar list mein values unique nahi hain, toh kisi aur stable unique value ka use karna better hai.


4. How do you use an ID as a key in React?

Answer:

Agar list objects ke form mein hai aur har object ke paas unique ID hai, toh ID ko key ke roop mein use karna generally best approach hai.

Example:

function Students() {
  const students = [
    {
      id: 101,
      name: "Rahul"
    },
    {
      id: 102,
      name: "Priya"
    },
    {
      id: 103,
      name: "Aman"
    }
  ];

  return (
    <div>
      {students.map((student) => (
        <p key={student.id}>
          {student.name}
        </p>
      ))}
    </div>
  );
}

export default Students;

Yahan:

key={student.id}

stable unique ID ko key bana raha hai.


5. Can you use the array index as a key in React?

Answer:

Technically, array index ko key ke roop mein use kiya ja sakta hai.

Example:

function App() {
  const courses = ["React", "Node.js", "Python"];

  return (
    <ul>
      {courses.map((course, index) => (
        <li key={index}>
          {course}
        </li>
      ))}
    </ul>
  );
}

export default App;

Lekin index ko key ke roop mein generally avoid karna chahiye jab list change, reorder, insert ya delete ho sakti hai.

Agar list static hai aur items kabhi reorder, insert ya delete nahi hote, toh index key acceptable ho sakti hai.


6. Why can using index as a key cause problems?

Answer:

Index kisi item ki permanent identity nahi hoti. Agar list ka order change ho jaye, same index kisi different item ko represent kar sakta hai.

Example:

Initial list:

0 → Apple
1 → Banana
2 → Mango

Agar beginning mein Orange add ho:

0 → Orange
1 → Apple
2 → Banana
3 → Mango

Ab indexes existing items ke saath shift ho gaye.

Aisi changing lists mein stable ID better hoti hai:

key={item.id}

instead of:

key={index}

Isliye dynamic lists ke liye stable unique keys prefer ki jati hain.


7. What happens if two list items have the same key?

Answer:

List ke sibling items ke keys unique honi chahiye.

Example:

const students = [
  { id: 1, name: "Rahul" },
  { id: 1, name: "Priya" }
];

Agar hum use karein:

{students.map((student) => (
  <p key={student.id}>
    {student.name}
  </p>
))}

Toh dono items ki key 1 hogi.

Ye incorrect hai because sibling list items ki identity ambiguous ho jayegi.

Better hai data mein genuinely unique ID ho:

const students = [
  { id: 1, name: "Rahul" },
  { id: 2, name: "Priya" }
];

Then:

key={student.id}

use kar sakte hain.


8. Should you generate random keys for React list items?

Answer:

Generally, random values ko keys ke roop mein use nahi karna chahiye.

Example:

<li key={Math.random()}>
  {product.name}
</li>

Ye problematic ho sakta hai because every render par new key generate hogi.

React ko lagega ki items naye hain, even when they represent the same data.

Instead, stable value use karein:

<li key={product.id}>
  {product.name}
</li>

Agar backend se unique ID mil rahi hai, toh us stable ID ko key ke roop mein use karna better hai.


9. Does the key prop become available inside the child component?

Answer:

No. key React ke liye special prop hai aur normal props ki tarah child component ke andar directly available nahi hoti.

Example:

function Student({ name, key }) {
  return (
    <p>
      {name} - {key}
    </p>
  );
}

Is tarah key ko child component ke andar read nahi karna chahiye.

Agar child ko ID ki zarurat hai, toh ID ko separate prop ke roop mein pass karein.

Correct Example:

function Student({ id, name }) {
  return (
    <p>
      {id} - {name}
    </p>
  );
}

function App() {
  const students = [
    { id: 101, name: "Rahul" },
    { id: 102, name: "Priya" }
  ];

  return (
    <div>
      {students.map((student) => (
        <Student
          key={student.id}
          id={student.id}
          name={student.name}
        />
      ))}
    </div>
  );
}

export default App;

Yahan:

key={student.id}

React ke liye hai, while:

id={student.id}

child component ko ID provide karta hai.


10. Build a practical Product List using stable Keys.

Answer:

Ab ek practical product list banate hain jisme har product ki unique ID ko key ke roop mein use kiya gaya hai.

Example:

function ProductList() {
  const products = [
    {
      id: 101,
      name: "Laptop",
      price: 55000
    },
    {
      id: 102,
      name: "Keyboard",
      price: 1500
    },
    {
      id: 103,
      name: "Mouse",
      price: 800
    }
  ];

  return (
    <div>
      <h2>Product List</h2>

      {products.map((product) => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>Price: ₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}

export default ProductList;

Yahan:

key={product.id}

har product ko stable identity provide karta hai.

Agar product list mein items update, remove ya reorder hote hain, toh unique IDs React ko items ko correctly identify karne mein help karti hain.


Key Takeaways

  • Keys React lists ke individual items ko identify karne mein help karti hain.
  • List render karte waqt stable keys use karni chahiye.
  • Database ya API se milne wali unique ID generally good key hoti hai.
  • Sibling list items ki keys unique honi chahiye.
  • Dynamic lists mein array index ko key ke roop mein avoid karna better hai.
  • Random values ko keys ke roop mein use nahi karna chahiye.
  • key React ke liye special prop hai aur child component ko normal prop ki tarah receive nahi hoti.
  • Agar child ko ID chahiye, toh ID ko separate prop ke roop mein pass karein.
  • Stable keys React ko list changes ko correctly track karne mein help karti hain.

FAQs

1. What is a key in React?

A key is a special value used by React to identify individual items in a rendered list.

2. Why does React need keys?

Keys help React identify which list items have changed, been added, removed, or reordered.

3. What is the best value to use as a React key?

A stable and unique ID associated with the item is usually the best choice.

4. Can I use an array index as a key?

Yes, but it should generally be avoided for lists that can change order, have items inserted, or have items removed.

5. Can two React list items have the same key?

Sibling list items should have unique keys. Duplicate keys can make list updates ambiguous and cause warnings.

6. Can I use Math.random() as a React key?

No. Random keys change between renders and can cause React to treat existing items as new elements.

7. Can I access the key prop inside a child component?

No. key is a special React prop. If the child needs the same ID, pass it separately as another prop.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top