0
0
ReactConceptBeginner · 3 min read

What is Key in React: Purpose and Usage Explained

In React, a key is a special string attribute used to uniquely identify elements in a list. It helps React track which items have changed, been added, or removed, improving rendering performance and avoiding bugs.
⚙️

How It Works

Imagine you have a list of items, like a to-do list, and you want to update it when things change. React uses the key to know which item is which, so it can update only the parts that changed instead of reloading the whole list. This is like having name tags on each item so React doesn’t get confused.

Without keys, React might mix up items when the list changes, causing unexpected behavior or slow updates. Keys must be unique among siblings to help React match the right elements during updates.

đź’»

Example

This example shows a list of fruits rendered with keys. Each li has a unique key based on the fruit name.

jsx
import React from 'react';

export default function FruitList() {
  const fruits = ['Apple', 'Banana', 'Cherry'];
  return (
    <ul>
      {fruits.map(fruit => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}
Output
<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>
🎯

When to Use

Use key whenever you create lists of elements in React, especially when rendering arrays with map(). Keys help React update the list efficiently when items change, are added, or removed.

For example, in dynamic lists like chat messages, task lists, or menus, keys prevent UI glitches and improve performance. Avoid using indexes as keys if the list can reorder or change, because it can cause bugs.

âś…

Key Points

  • Keys must be unique among siblings to identify elements.
  • Keys help React optimize rendering by tracking changes in lists.
  • Use stable IDs or unique values as keys, not array indexes if the list changes.
  • Keys are not passed as props to components; they are used internally by React.
âś…

Key Takeaways

Always provide a unique key prop for list elements in React to help with efficient updates.
Keys help React identify which items changed, preventing UI bugs and improving performance.
Avoid using array indexes as keys if the list can reorder or items can be added/removed.
Keys are used internally by React and do not appear as props inside components.