I understand that it is best practice when gearing a list of items in REACT to assign a unique, stable, key to each item in order to make redeeming more efficient. I also understand that this in order to be stable, this key should NOT be generated based on something like the item’s index on the source array.
I was wondering if any REACT expert might have a go-to technique for generating stable keys keys , not based on the index , when you have , a generic, non-unique, array?
Example, say you were trying to build a component that renders a UL from the following data array:
let data = [‘HTML’, ‘Bootstrap’,‘javascript’,‘CSS’, ‘javascript’,‘HTML’, ‘javascript’,‘javascript’,‘HTML’, 'CSS,‘PHP’]
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort
The question though is where such data is coming from; if it’s getting created at runtime (from user input, for instance) you might just assign an increment ID to each new item.
Edit: x-post… nice idea to serialize the item value for more stable index-based keys. :-)
@James_Hibbard Thank you, for the tips.That method would work in the case the data set only contains unique values, tho. I will look into UUID.
@m3g4p0p, This question arose from doing a simple task tracker demo project. I observed that some low level data that was just an array (which also had repeated values) The data low level data beign read from a database. What I mean by low level is that the info contained in the array are not object literals, and cannot be assigned any sort of permanent id without convoluting the data set.
it’s the opposite, i am sure it could often contain duplicate values. I like m3g4pop’s idea of just having an increment variable; that could be easy to implement in class components but it leves me wondering how to do the same thing with functional components ( as REACT hooks become ever more popular)
I’m not sure if this has any noteworthy impact, but if you assemble the keys in the render return value, then removing an item would also cause all following keys to change… so wouldn’t it be better to generate IDs upfront? Like e.g.
const allItems = [
'HTML',
'Bootstrap',
'JavaScript',
'HTML'
].map((value, index) => ({
value,
id: value + index
}))
Edit: Scratch that, it won’t let you easily add items later on… you’d have to elaborately compute the new item IDs from the current data, but then you might just as well go back to increment IDs. ^^