I have a use case where I want to assign unique ids to each element of array while iterating over it. Note, This array contains duplicate values. I want to use index as a key in react element, but linter rules do not allow me to use index as a key. I thought of using System tics? Is there a way i can get system ticks so that on every instruction execution, I get a new value? If yes, What is the recommended precision?
-
1`new Date().getTime();` or `new Date().getTime().toString(16);` or even [create a GUID](https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript) – Reinstate Monica Cellio Jan 16 '18 at 12:55
2 Answers
I would suggest to use neither indices nor system ticks as both options take you away from the functionality that the key is supposed to provide.
In the documentation it says: "Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity"
So there are a variety of options:
- You can create a function to generate unique keys/ids/numbers/strings and use that
- You can make use of existing npm packages like uuid, uniqid, etc
- You can also generate random number like new Date().getTime(); and prefix it with something from the item you're iterating to guarantee its uniqueness
- Lastly, you can use the unique ID you get from the database, if you get it (hard to say without seeing your data)
However: Keys should be stable, predictable, and unique. Unstable keys (like those produced by Math.random()) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
You can read more here: https://reactjs.org/docs/reconciliation.html#keys
So there is no perfect answer for that. It depends on your use case...
- 597
- 4
- 11
-
Thank you :) Although you are answering for a specific question, it is broad enough to serve as a guideline. Because of this answer I also discovered uuid and uniqid: they are great. – viery365 Sep 26 '18 at 10:16
Even though @Archer 's approach might already be feasible enough, I provide this solution that I mostly use in cases like the ones described by the OP ...
var createId = (
/* [https://github.com/broofa/node-uuid] - Robert Kieffer */
(window.uuid && (typeof window.uuid.v4 === 'function') && window.uuid.v4)
/* [https://gist.github.com/jed/982883] - Jed Schmidt */
|| function b(a){return a?(a^Math.random()*16>>a/4).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,b)}
);
console.log('createId() : ', createId());
console.log('createId() : ', createId());
console.log('createId() : ', createId());
.as-console-wrapper { max-height: 100%!important; top: 0; }
- 8,830
- 2
- 27
- 33