Everything you really need to know about React keys

Prince Anyaoha
2 min readJan 17, 2022
Photo by Everyday basics on Unsplash

In React, keys are used to identify an item in a list let’s say we have a component like this

React gives a warning for this component “warning: each child on a list should have a unique key prop”. If we add a key prop/attribute to the li like so

the warning goes away, but what exactly are these keys used for and why should they be ‘unique’.

Keys in React are used as identifiers, they are used to keep track of what components changed, was removed, or added, because of this, a key should be unique to a list item and should not change while operations are made on the list. The code examples above involve a static list that doesn't change but in real applications, we have list data coming from HTTP requests, and sometimes we do operations on them like filtering, deleting, or even paginations if the resource is more than just a few. These operations mean the list data will have to change a few times and the components will be rerendered, this is where keys become super important for React to identify if an item is new, has changed, or was deleted. It is important for react to know this for efficient rerendering.

Some bad practices you might come across is using indices or Math.random as keys, keys are used for identification not numbering so using indices on a list that changes over time would cause some unusual behavior in the application because when the number of items to render changes, the indices change so the keys would change, if there are state changes or prop changes to items in the list, react might try to update the wrong item on the list. You should only use indices as keys when the list is one that would never be changed, filtered, or reordered. Using Math.random has a similar effect as the function would rerun every time the list changes most likely generating a new number and it's generally unstable.

A good practice is to use the values being rendered as keys as they would most likely be unique (cause why would you want to display a value more than once in a list, we saw it the first time 😐) or if the list item component is being passed an object, you can use a field in the object that is unique across the list as the key.

Keys are not passed down to the component as props, they are used internally by React so you cannot access a key from inside a component like a normal prop. Also, keys do not need to be globally unique, they just need to be unique compared to their siblings in a list, and when a key changes, React re-renders the component.

Happy coding 🙂.

--

--