Skip to main content

Why do we need keys for React lists?

Keys are a unique value that we must pass to the key prop when we are using the .map() function to loop over an element or a component.

If we are mapping over an element, it would look like this:

posts.map(post => <li key={post.id}>{post.title}</li>)

Or like this if we are mapping over a component:

posts.map(post => <li key={post.id}>{post.title}</li>)

And in both case, we need to add a key that is a unique value, otherwise React will warn us.

Why? Because keys tell React which element or component is which in a list.

Otherwise, if we were to try to change items in this list by inserting more or editing them in some way, React wouldn’t know the order to put them in.

This is because React takes care of all of the business of updating the DOM for us (using a virtual DOM), but keys are necessary for React to update it properly.