Is using the index for the key prop in react good practice?

So, I’m trying to understand the key prop for lists in react.

I understand that the key prop is needed when rendering lists in react. Generally, from what I’ve seen people tend to use a unique ID that is found within each object in a list.

However, I’ve just learned that people will use the index of each item through the second parameter of MAP as the key when an ID is unavailable.

now my question is what would stop someone from just always using the index as the key? It would always be unique and seems like a very easy way of doing things. Is there any reason you couldn’t always do this to simplify things? I still don’t fully understand the key prop so maybe I’m missing something.

Right but if you add an item anywhere except the end to the collection being mapped over, what happens?

Edit: just to clarify, the key is an indication to React that an element probably hasn’t changed. React has already processed it, already done the work it needs. If you have a collection of components, and you add/remove a component from the collection, the ones with the same ID don’t need any extra processing done. If they didn’t have that key, then React would need to [re]process every component to make sure.

Maybe there’s a filter or sort UI that changes the list, but not the content of the items within it. In this case, item X might sometimes have index 0, or index 99, or index 42. If you were using the index as the key, React would rerender that item each time the filter/sort changed. That’s the downside.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.