Reputation: 5292
Problem is the following:
I have data in form of a list of a few thousand elements. Some of them are duplicates, and there might be the chance of having duplicate keys as well then.
Because I have no real "ID" or anything which would give me the opportunity to give all elements their id as unique keys, is it okay to use Math.random()
instead?
As far as I understood, the keys are mainly used by react to differentiate the components. I think as far as I don't really have anything to do with the keys in my code, this should go fine? To ensure that there will be no duplicate number I might as well divide two math randoms with each other to get an almost certainly unique key.
Is this a good practice? Can I use this without having to worry about anything?
Upvotes: 92
Views: 101948
Reputation: 37
As additional point to @Markus-ipse's answer:
2.5 use your own unique id generator
Example:
const nextId = Ract.useRef(0);
...
const addToList = (item) => {
item.myId = nextId.current++;
...
};
This will simply increase ref's value by one each time you addToList
and thus generate unique value during life of your component.
Upvotes: 0
Reputation: 1
MathRandom() is not prefereble.
KEY RULES
index❌ => if you sort, index can change so it's not invariant Math.random()❌ => it also invariant
I personaly use uuid(), uuid() output is also invariant but ajusting timing to set uuid value. like below. I tackling this key problem.
If something wrong or notice something , please tell me! I also want to know better solution!
I hope this infomation help🥳
Upvotes: 0
Reputation: 2743
Other answers say that Math.random()
is a bad idea, but that's only half true. It's perfectly acceptable to use Math.random()
if we do it when the data is initially received, rather than in the render.
For example:
function SomeComponent() {
const [items, setItems] = React.useState(() => []);
React.useEffect(() => {
fetch('/api/data')
.then((res) => res.json())
.then((data) => {
const itemsWithIds = data.map((item) => {
return {
...item,
id: Math.random(),
};
});
setItems(itemsWithIds);
});
}, []);
return (
<div>
{items.map((item) => (
<Item key={item.id} item={item} />
))}
</div>
);
}
Right when I receive the data, I map over each item in the list and append a unique ID with Math.random()
. When rendering, I use that previously-created ID as the key.
The most important thing is that we don't re-generate the key on each render. With this sort of setup, we only generate the key once, when we receive the data from our API.
You can use this pattern in just about every circumstance, even for local data. Right before you call the state-setter (or, before you initialize the state hook), you can generate a unique ID for each item.
You can also use crypto.randomUUID()
instead of Math.random() to generate a uuid instead of a random number.
Upvotes: 6
Reputation: 2219
I had a use case where I am rendering a list of tiles based on data fetched from a remote API. For example, the data looks like this -
[
{referrals: 5, reward: 'Reward1'},
{referrals: 10, reward: 'Reward2'},
{referrals: 25, reward: 'Reward3'},
{referrals: 50, reward: 'Reward4'}
]
This list can be modified on the client-side where a random entry (tile) in the list can be spliced/removed, or a new entry (tile) can be added at the end of the list.
There could be duplicate entries in this list so I cannot create a hash/unique key based on the content of the list entry.
Initially, I tried using array index as a key to render the tiles but in this case what ends up happening is, if I splice the entry at index 3
for example, then the entry at index 4
takes its place at index 3
, and for React, since key 3
is intact, while rendering, it just removes the tile at index 4
while keeping the original tile at index 3
still visible, which is undesired behavior.
So based on the above ideas shared by @josthoff and @Markus-ipse I used a client-side self-incrementing counter as a key (Check https://stackoverflow.com/a/46632553/605027)
When data is initially fetched from the remote API, I add a new key attribute to it
let _tiles = data.tiles.map((v: any) => (
{...v, key: this.getKey()}
))
So it looks like below
[
{referrals: 5, reward: 'Reward1', key: 0},
{referrals: 10, reward: 'Reward2', key: 1},
{referrals: 25, reward: 'Reward3', key: 2},
{referrals: 50, reward: 'Reward4', key: 3}
]
When adding a new entry (tile), I make another call to this.getKey()
. By doing this, every entry (tile) has a unique key and React behaves as intended.
I could've used a random hexadecimal key or UUID generator here but for simplicity I went ahead with self-incrementing counter.
Upvotes: 1
Reputation: 13164
From react documentation:
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.
Upvotes: 20
Reputation: 1
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 should add a key to each child as well as each element inside children.
This way React can handle the minimal DOM change.
Please go through the https://reactjs.org/docs/reconciliation.html#recursing-on-children. Here you will get best explanation with example of code.
Upvotes: 1
Reputation: 7396
Every time a component's key changes React will create a new component instance rather than update the current one, so for performance's sake using Math.random() will be sub-optimal to say the least.
Also if you'll be reordering your list of components in any way, using the index as key will not be helpful either since the React reconciler will be unable to just move around existing DOM nodes associated with the components, instead it will have to re-create the DOM-nodes for each list item, which, once again will have sub-optimal performance.
But to reiterate, this will only be a problem if you will be re-ordering the list, so in your case, if you are sure you will not be reordering your list in any way, you can safely use index as a key.
However if you do intend to reorder the list (or just to be safe) then I would generate unique ids for your entities - if there are no pre-existing unique identifiers you can use.
A quick way to add ids is to just map the list and assign the index to each item when you first receive (or create) the list.
const myItemsWithIds = myItems.map((item, index) => { ...item, myId: index });
This way each item get a unique, static id.
tl;dr How to choose a key for new people finding this answer
If your list item have a unique id (or other unique properties) use that as key
If you can combine properties in your list item to create a unique value, use that combination as key
If none of the above work but you can pinky promise that you will not re-order your list in any way, you can use the array index as key, but you are probably better of adding your own ids to the list items when the list is first received or created (see above)
Upvotes: 108
Reputation: 175
Is this a good practice? Can I use this without having to worry about anything?
No and no.
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.
Let me illustrate this with a simple example.
class Input extends React.Component {
handleChange = (e) => this.props.onChange({
value: e.target.value,
index: this.props.index
});
render() {
return (
<input value={this.props.value} onChange={this.handleChange}/>
)
}
};
class TextInputs extends React.Component {
state = {
textArray: ['hi,','My','Name','is']
};
handleChange = ({value, index}) => {
const {textArray} = this.state;
textArray[index] = value;
this.setState({textArray})
};
render(){
return this.state.textArray.map((txt, i) => <Input onChange={this.handleChange} index={i} value={txt} key={Math.random()}/>)
// using array's index is not as worse but this will also cause bugs.
// return this.state.textArray.map((txt, i) => <Input onChange={this.handleChange} index={i} value={txt} key={i}/>)
};
};
Why can't i type in more than one character in the inputs you ask?
It is because I am mapping multiple text inputs with Math.random() as key prop. Every time I type in a character the onChange prop fires and the parent component's state changes which causes a re-render. Which means Math.random is called again for each input and new key props are generated.So react renders new children Input components.In other words every time you type a character react creates a new input element because the key prop changed.
Read more about this here
Upvotes: 8
Reputation: 2309
I think its not correct to give Math.random() for components keys, reason is when you generate random number it is not guaranteed not to get same number again. It is very much possible that same random number is generated again while rendering component, So that time it will fail.
Some people will argue that if random number range is more it is very less probable that number will not be generated again. Yes correct but you code can generate warning any time.
One of the quick way is to use new Date() which will be unique.
Upvotes: -3