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.
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.

Share
Published by
Saransh Kataria

Recent Posts

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…

2 weeks ago

Native popover API in HTML

Popovers have been a problem that was typically solved by using a third-party solution. But…

3 weeks ago

Node.js 20.6 adds built-in support for .env files

Node.js 20.6 added built-in support for the .env file. This is an excellent addition to the platform…

4 weeks ago

Object destructuring in TypeScript

Object destructuring is a powerful ES 6 feature that can help developers write cleaner code.…

1 month ago

Improve git clone performance in a CI pipeline

Have you felt particularly annoyed by the time it takes to clone a large repository,…

2 months ago

Fix: Hydration failed because the initial UI does not match what was rendered on the server

Within a React or Next.js app, if you encounter the error "Hydration failed because the…

2 months ago
Advertisements