1

I'm rendering a list in my react app where:

  • Only new elements will be appended to the end of the list.
  • Every time an element is removed, it will only be the last element.

Given these conditions as well as not having the intention to reorder elements in any way. Can I use the index as the key prop without having any problem?

1
  • Whilst you can the only considerations you might take into account are 1. Are you working on a team that may ignore or not be aware of your conditions and 2. that you're likely to never change the functionality at a later day. Commented Jun 17, 2020 at 12:09

1 Answer 1

1

Yes, it is!

You can read what React docs says in here: https://reactjs.org/docs/lists-and-keys.html#keys

The main is this: We don’t recommend using indexes for keys if the order of items may change. T

You can also check this article: https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

According to it, if you meet this conditions:

  1. the list and items are static – they are not computed and do not change;
  2. the items in the list have no ids
  3. the list is never reordered or filtered.

You should be good to go.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.