Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does using `index` as the key in multiple `.map( element, index)` affect React's reactivity?

If you have:

<div>
    { books.map( ( book, index ) => (
        <div key={ index }>
            { book.label }
        </div>
    ) ) }
    { movies.map( ( movie, index ) => (
        <div key={ index }>
            { movie.label }
        </div>
    ) ) }

</div>

As the index would be 0, 1, 2, etc. That means there will be divs with the "same" key value.

Does the index being inside a .map() make it unique or should each key be set like this to be unique in the entire app: <div key={ 'book-' + index }> and <div key={ 'movie-' + index }>?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A key being unique to a particular returned .map is enough. Your current code is fine – in that sense.

But it would be better not to use the index as the key, in general – if the books or movies arrays ever have items removed or shifted around, the index will not be reliable as a key, because the same "movie" would then have a different index. Better to pick something unique from those objects – if no two movies will have the same movie.label, for example, that could be a good choice for a key. (or if you have anything like a unique .movieId property, that’d work too)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading