Why Key is Important in React: Explanation and Examples
In React, the
key prop is important because it helps React identify which items in a list have changed, been added, or removed. This improves rendering performance and prevents UI bugs by giving each element a stable identity.Syntax
The key prop is added to elements inside a list to give each one a unique identifier. It looks like this:
<li key={uniqueValue}>Item</li>: Assigns a unique key to each list item.uniqueValue: Usually a string or number that uniquely identifies the item.
React uses this key to track elements between renders.
jsx
const items = ['Apple', 'Banana', 'Cherry']; const list = items.map((item) => ( <li key={item}>{item}</li> ));
Example
This example shows a list of fruits rendered with keys. React uses the keys to update only changed items when the list changes.
jsx
import React, { useState } from 'react'; export default function FruitList() { const [fruits, setFruits] = useState(['Apple', 'Banana', 'Cherry']); function addFruit() { setFruits([...fruits, 'Date']); } return ( <> <ul> {fruits.map((fruit) => ( <li key={fruit}>{fruit}</li> ))} </ul> <button onClick={addFruit}>Add Date</button> </> ); }
Output
A list showing Apple, Banana, Cherry and a button labeled 'Add Date'. Clicking the button adds 'Date' to the list without re-rendering all items.
Common Pitfalls
Common mistakes with key include:
- Using indexes as keys can cause bugs when list items reorder or delete.
- Not providing keys causes React to re-render all items, hurting performance.
- Using non-unique keys leads to unpredictable UI behavior.
Always use stable, unique keys like IDs or unique strings.
jsx
const items = ['Apple', 'Banana', 'Cherry']; // Wrong: Using index as key const listWrong = items.map((item, index) => ( <li key={index}>{item}</li> )); // Right: Using unique item as key const listRight = items.map(item => ( <li key={item}>{item}</li> ));
Quick Reference
| Key Usage Tips |
|---|
| Always assign a unique and stable key to list items. |
| Avoid using array indexes as keys when list order can change. |
| Keys help React optimize rendering and avoid bugs. |
| Use IDs or unique strings from your data as keys. |
| Missing keys cause React to re-render entire lists unnecessarily. |
Key Takeaways
Keys give each list item a unique identity for React to track changes efficiently.
Never use array indexes as keys if the list can reorder or items can be removed.
Unique and stable keys prevent UI bugs and improve rendering performance.
Always provide keys when rendering lists in React components.
Use meaningful unique values like IDs or unique strings from your data as keys.