Keys
Is
key={crypto.randomUUID()}
an okay-ish way of setting keys in TSX/JSX maps? I won't be needing the key for anything later but I'm not sure if this is a good way of going by itSolution:Jump to solution
you want to ensure that your key is something that is the same for the same state and different for all other states, a uuid is perfectly fine for this but it should not be randomly generated on the fly
6 Replies
No, generally you want something stable and related to the item it is referencing. Especially when its React because it allows for render optimizations for the lists.
https://react.dev/learn/rendering-lists
usually I use an index (second parameter of a map() method) as the key. Not sure if this is enough for your solution.
Biome recommends to not use the index of the map, eslint too, iirc
React recommends to use an ID that’s predetermined in the data, so isn’t this the same as an index from the map?
it's not great if you mutate your array, e.g. remove the element at key=5 so that the current key=6 element becomes key=5, which can mess stuff up
Solution
you want to ensure that your key is something that is the same for the same state and different for all other states, a uuid is perfectly fine for this but it should not be randomly generated on the fly
Oh alright, that makes sense. Thanks for the help