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 it
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
Jump to solution
6 Replies
JacobMGEvans
JacobMGEvans2d ago
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
Richard
Richard2d ago
usually I use an index (second parameter of a map() method) as the key. Not sure if this is enough for your solution.
filyys
filyysOP2d ago
Biome recommends to not use the index of the map, eslint too, iirc
You need to give each array item a key — a string or a number that uniquely identifies it among other items in that array
You need to give each array item a key — a string or a number that uniquely identifies it among other items in that array
React recommends to use an ID that’s predetermined in the data, so isn’t this the same as an index from the map?
msvcredist2022
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
msvcredist2022
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
filyys
filyysOP2d ago
Oh alright, that makes sense. Thanks for the help

Did you find this page helpful?