error: Do not use Array index in keys

When you use index of an array as a key, React will optimize and not render as expected. What happens in such a scenario can be explained with an example.

Suppose the parent component gets an array of 10 items and renders 10 components based on the array. Suppose the 5th item is then removed from the array. On the next render the parent will receive an array of 9 items and so React will render 9 components. This will show up as the 10th component getting removed, instead of the 5th, because React has no way of differentiating between the items based on index.

Therefore always use a unique identifier as a key for components that are rendered from an array of items.

You can generate your own unique key by using any of the field of the child object that is unique as a key. Normal, any id field of the child object can be used if available.

Edit : You will only be able to see the behavior mentioned above happen if the components create and manage their own state, e.g. in uncontrolled textboxes, timers etc. E.g. React error when removing input component

Leave a Comment