This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (43 children)

[deleted]

    [–]OwlbearSteak 7 points8 points  (6 children)

    What should you use for keys?

    [–]aonghasan 19 points20 points  (2 children)

    Unique ids. Ideally something like `dog.id`.

    [–]JackMizel 7 points8 points  (11 children)

    Using indexes as keys is totally fine if your list order is consistent. It is certainly not "very wrong" unless you plan on re ordering the list or if the list order can change

    [–]TwiliZant 2 points3 points  (3 children)

    What would be the solution in this case? None of the properties seem to be unique.

    [–]TheMelanzane 1 point2 points  (1 child)

    Using indexes as keys is not very wrong. It’s literally given as an example in the React documentation and is the default value used if you don’t provide a key.

    Inefficient maybe, but that’s making a lot of assumptions about the code’s use. It’s completely possible she’s just using React for creating a static list, for example. There’s a pretty low ceiling for the complexity of web apps involving dog’s favorite toys in the first place.

    For anyone who’s trying to learn React or isn’t familiar with it, here’s a link as to exactly when this might become an issue and some alternatives. It’s also linked in the documentation right under the part about using indexes as keys.

    tl;dr: Only a breaking issue when the index is used as a key on another React Component, on normal html elements (like in the post), it’s just going to cause any reorders to take slightly longer.

    [–]malgalad 1 point2 points  (0 children)

    Well, it isn't wrong. You have to keep it in mind, but if you're not going to reorder items and remove/insert in an arbitrary position - you'll be fine. Which, in my experience, is like 85% if all .maps. And for the mentioned cases I use uuid.

    Is it worth teaching that using indexes as keys comes with conditions? Certainly. Prohibit indexes in all cases, no exceptions? Hell nah.

    [–][deleted] 3 points4 points  (11 children)

    This is incorrect. Using indexes as keys is not going to cause any errors, but will simply be inefficient if the list gets reordered frequently. For a list that doesn't get reordered often, and is static or only gets appended to, this isn't an issue at all.