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')
);

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?

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

Software Consultant, Author, Speaker, React Native|React|GraphQL Dev & Indian Classical Musician http://adhithiravichandran.com/

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