React Keys

In React, keys are used to uniquely identify elements in a list. Keys help React efficiently update and render lists by identifying which items have changed, added, or removed. Without keys, React would have to re-render the entire list every time there is a change, which can impact performance.

1 Why Keys Are Important

Keys are essential for lists where items can be dynamically added, removed, or updated. React uses keys to identify which list items correspond to each rendered element. This makes updates faster and ensures consistent behaviour.

2 Example: Using Array Index as Keys

In this example, we use the array index as a key to render a list. This approach works for simple lists where the items do not change dynamically.

App.js

</>
Copy
import React from 'react';

function SimpleList() {
  const items = ['Apple', 'Banana', 'Cherry'];

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

export default SimpleList;

Explanation:

  • key={index}: Uses the array index as a key.
  • This approach is sufficient for static lists but may cause issues if the list items are reordered or dynamically updated.

Output: