4 ms·
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-re
by mediumdeviation 4y ago
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-your-key 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-state#option-2-resetting-state-with-a-key https://beta.reactjs.org/learn/preserving-and-resetting-stat... which is unlikely to be what you want.
- Swizec 4y ago> 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.
- isleyaardvark 4y agoI 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.
- orangepanda 4y agoIts 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
- thrashh 4y agoNot 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.
- deleted 4y ago[deleted]