Why do I need Keys in React Lists?

React List and Keys

Rendering a simple List component

function ListComponent(props) {
const listItems = myList.map((item) =>
<li>{item}</li>
);
return (
<ul>{listItems}</ul>
);
}
const myList = ["apple", "orange", "strawberry", "blueberry", "avocado"];
ReactDOM.render(
<ListComponent myList={myList} />,
document.getElementById('root')
);
  • apple
  • orange
  • strawberry
  • avocado

How do you use Keys in Lists?

function ListComponent(props) {
const listItems = myList.map((item) =>
<li key={item.id}>
{item.value}
</li>
);
return (
<ul>{listItems}</ul>
);
}
const myList = [{id: 'a', value: 'apple'},
{id: 'b', value: 'orange'},
{id: 'c', value: 'strawberry'},
{id: 'd', value: 'blueberry'},
{id: 'e', value: 'avocado'}];
ReactDOM.render(
<ListComponent myList={myList} />,
document.getElementById('root')
);

Can I just use indexes as keys? — Only under some exceptions

const todoItems = todos.map((todo, index) =>
// Only do this if items have no stable IDs
<li key={index}>
{todo.text}
</li>
);

What are some exceptions where it is safe to use index as key?

  1. If your list is static and will not change.
  2. The list will never be re-ordered.
  3. The list will not be filtered (adding/removing items from the list).
  4. There are no ids for the items in the list.

Keys need to be Unique, but only among its siblings

Keys don’t automatically get passed as a prop to the component

const content = items.map((item) =>
<MyComponent
key={item.id}
id={item.id}
title={item.title} />
);

Conclusion

  1. Lists are performant heavy and need to be used carefully.
  2. Make sure every item in the list has a unique key.
  3. It is prefered to not use indexes as a key unless you know for sure that the list is a static list (no additions/re-ordering/removal to the list).
  4. Never use unstable keys like Math.random() to generate a key.
  5. React will run into performance degradation and unexpected behaviour if unstable keys are used.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adhithi Ravichandran

Software Consultant, Author, Speaker, React Native|React|GraphQL|Cypress Dev & Indian Classical Musician