DEV Community

Discussion on: My most frequent React errors and how you fix them

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

You should not use nanoid, or any other random ID generator, to create keys for your React array elements. In fact, it says, right on their README, that

There’s currently no correct way to use nanoid for React key prop since it should be consistent among renders.

Using a random random generator for keys forces the the reconciliation process to always view every element in the array as "new" or "changed", which forces it to rerender - and that can cause some nasty side effects.

I was actually learned this the hard way several years ago when I was using my own custom random ID function with Material UI's Collapse component. You can see an explanation of the issue here:

stackoverflow.com/questions/513719...

Collapse
 
souksyp profile image
Souk Syp.

That's good to know

Collapse
 
kieran6roberts profile image
Kieran Roberts

You're right, not sure how I missed this. Removed it for now. Thanks for the input!