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.
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.
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.
We talked about why should we not use index as key in React Lists. But what should we use then? Some alternatives are:
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>
);
}
JavaScriptconst 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>
);
}
JavaScriptuseId
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>
);
}
JavaScriptDevelopers 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.
I recently switched completely to the Brave browser and have set ad blocking to aggressive…
I was preparing a slide deck for a hackathon and decided to put in a…
I have been using npx a lot lately, especially whenever I want to use a…
Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…
While working on a project, I wanted to do an integrity check of a file…
Popovers have been a problem that was typically solved by using a third-party solution. But…
View Comments
please don't mislead people:
PitfallDo not call
useId
to generate keys in a list. Keys should be generated from your data.Thanks for leaving a comment. I thought I had added a note about it but apparently I did not. Updated the post with a note!