React

Why should we not use index as key in React Lists

Advertisements

When working with React, developers often come across the need to render lists of items efficiently. Every item in a list needs to have a key prop assigned to it. It is essential for enabling React to track changes made to these items. Using array indexes as these keys is a common error made by beginners. Let us discuss why we should not use array index as key in React lists. We will also go into what alternatives exist and can be used for better performance and consistency.

What are Keys in React?

Keys in React are unique string attributes that are used to identify what items in a list have been added, updated, or removed from DOM. They play a crucial role in optimizing the re-rendering process since they guarantee that only changed elements get updated, which improves the application’s performance.

The Issue with Array Indexes as Keys

Using array indexes as keys might appear to be easier at first glance, but it can introduce problems later. To start with, array indexes are not stable identifiers. React may render extra components if the array’s order is altered by additions or deletions, as this affects the indexes. This can lead to performance issues and it can also potentially cause conflicts with sibling components and inconsistent UI.

Alternatives to Array Indexes for Keys

We talked about why should we not use index as key in React Lists. But what should we use then? Some alternatives are:

  1. Use Unique Identifiers: The most reliable alternative is using unique identifiers such as IDs or slugs. This ensures the stability of keys, irrespective of whether the list items are reordered or modified. For example, if we have a list of blog posts with unique ID’s, we can use it as the key.
const posts = [
  { id: 'post-1', title: 'React Essentials' },
  { id: 'post-2', title: 'Understanding Hooks' },
  // ... other posts
];

const Posts = () => {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}
JavaScript
  1. Combine Multiple Values to Generate a Composite Key: If unique IDs are unavailable, a composite key can be generated by concatenating several item properties to create a unique string.
const todoItems = [
{ userId: 1, title: 'Buy milk', date: '2023-04-30' },
{ userId: 2, title: 'Send email', date: '2023-04-30' },
// … other items
];

const TodoList = () => {
  return (
    <ul>
      {todoItems.map((item) => (
        <li key={`${item.userId}-${item.date}-${item.title}`}>
          {item.title}
        </li>
      ))}
    </ul>
  );
}
JavaScript
  1. Use the useId Hook in React 18: useId, a brand-new built-in hook in React 18, creates a distinct ID that remains consistent between renders.

    Note: Only use this if the data is never going to change and there is no unique ID available in your form data.
import { useId } from 'react';

function ListItem({ children }) {
  const uniqueId = useId();
  return <li key={uniqueId}>{children}</li>;
}

function MyList({ items }) {
  return (
    <ul>
      {items.map((itemText) => (
        <ListItem>{itemText}</ListItem>
      ))}
    </ul>
  );
}
JavaScript

Developers can fully utilize React’s effective update mechanisms and create apps that are more resilient and maintainable by adhering to these best practices. Hope this post helped you learn more about React’s internals and if you have any questions, leave a comment below.

Saransh Kataria

Born in Delhi, India, Saransh Kataria is the brain behind Wisdom Geek. Currently, Saransh is a software developer at a reputed firm in Austin, and he likes playing with new technologies to explore different possibilities. He holds an engineering degree in Computer Science. He also shares his passion for sharing knowledge as the community lead at Facebook Developer Circle Delhi, NCR which is a developer community in Delhi, India.

View Comments

Share
Published by
Saransh Kataria

Recent Posts

Remapping keyboard keys to avoid Carpal Tunnel

I am terrible at optimizing my keyboard layout for anything. But off lately, my little…

4 weeks ago

Fixing cookies are blocked for a website with shields down on Brave

I recently switched completely to the Brave browser and have set ad blocking to aggressive…

5 months ago

Generating a QR code using Node.js

I was preparing a slide deck for a hackathon and decided to put in a…

6 months ago

How to clear the global npx cache

I have been using npx a lot lately, especially whenever I want to use a…

6 months ago

Copy/Pasting output from the terminal

Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…

7 months ago

How To Get The Hash of A File In Node.js

While working on a project, I wanted to do an integrity check of a file…

8 months ago
Advertisements