What is Key in React: Purpose and Usage Explained
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.
import React from 'react'; export default function FruitList() { const fruits = ['Apple', 'Banana', 'Cherry']; return ( <ul> {fruits.map(fruit => ( <li key={fruit}>{fruit}</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.