0
0
Reactframework~5 mins

Importance of keys in React

Choose your learning style9 modes available
Introduction

Keys help React keep track of items in a list. They make updates faster and avoid bugs.

When rendering a list of items like a list of names or products.
When items in a list can be added, removed, or reordered.
When you want React to update only changed items, not the whole list.
Syntax
React
<Component key={uniqueValue} />

The key must be unique among siblings.

Use stable values like IDs, not indexes, if the list can change.

Examples
Using the item string as a key when items are unique and stable.
React
const list = ['apple', 'banana', 'cherry'];

return (
  <ul>
    {list.map(item => <li key={item}>{item}</li>)}
  </ul>
);
Using index as key is okay if list never changes order or items.
React
const list = ['apple', 'banana', 'cherry'];

return (
  <ul>
    {list.map((item, index) => <li key={index}>{item}</li>)}
  </ul>
);
Sample Program

This component shows a list of fruits. Each fruit has a unique key. When you add a new fruit, React updates only the new item.

React
import React, { useState } from 'react';

export default function FruitList() {
  const [fruits, setFruits] = useState(['apple', 'banana', 'cherry']);

  function addFruit() {
    setFruits([...fruits, 'orange']);
  }

  return (
    <div>
      <button onClick={addFruit} aria-label="Add orange fruit">Add Orange</button>
      <ul>
        {fruits.map((fruit, index) => (
          <li key={index}>{fruit}</li>
        ))}
      </ul>
    </div>
  );
}
OutputSuccess
Important Notes

Never use random values for keys because React needs keys to be stable between renders.

Keys help React identify which items changed, were added, or removed.

Summary

Keys must be unique and stable to help React update lists efficiently.

Use keys when rendering lists to avoid bugs and improve performance.