Hacker News new | past | comments | ask | show | jobs | submit login

Right, I'm not sure the author understands key either. It's an optimization to help React identify insertion / removal / reordering of array items between re-render. https://beta.reactjs.org/learn/rendering-lists#where-to-get-...

Giving every item a new key on every update does not help with that - in fact it is likely strictly worse than just using index since it will cause every item to re-mount every update https://beta.reactjs.org/learn/preserving-and-resetting-stat... which is unlikely to be what you want.




Its not an optimisation, its about state management.

React can’t see the difference between a reorder and remove&insert. When reordering items the state should be moved as well; when removing and inserting a new item, state should reset.

Using an array index is equivalent to silencing the error


Not necessarily.

It depends on what your data source is. If it’s a stable sorted list that only ever gets appended at the end, you can use the index.

At the end of the day, there is no hard fast rule for the key. You have to know what your data source is.

You have to know what you’re doing.


> Giving every item a new key on every update does not help with that

fwiw the author specifies says not to do this. The advice is to generate a unique ID when items are created, not when they’re rendered.


I was going to reply the same thing. I do have a problem with the author presenting that as a default solution instead of a workaround if the item doesn't have a unique identifier, which I have found to be uncommon.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: