typescript:S6479 fails to account for keys that include other values with an index

Typescript rule S6479 warns us not to use indexes for keys in arrays, but does not take into account when a key uses both an index and another value.

True positive:

{items.map((item, index) => <Item key={index} item={item} />

False positive:

{items.map((item, index) => <Item key={`${item.id}-${index}`} item={item} />

The first situation doesn’t take into account the content being rendered, which is a problem. If the content changes, but the key doesn’t, React won’t know and not rerender it.

The second situation arises when there are duplicate items in an array, which can happen in lists of text strings or non-DB-derived objects, for example. In this situation, the index is required to prevent React from throwing up duplicate key errors. By combining the index with the key, we sacrifice order-agnostic memoization for uniqueness. This is preferable to breaking React’s requirement of unique keys.

I’d recommend tightening the scope of TS:6479 to keys that are index-only. If another variable associated with the element in the array is included, that should be acceptable. I don’t know if the parser can get that specific, or if it is enough to say “another variable is referenced,” but this seems a valid alternative.

Hello @lunarlandis,

Thank you for taking the time to provide your valuable feedback, and a warm welcome to the Sonar community!

Your scenario highlights a pertinent use case that our rule should encompass. To address this, I have created a ticket to introduce a specific exception for this case.

We are committed to addressing it promptly.

Best regards,
Yassin

1 Like

Thank you! :slight_smile: