React expects a unique identifier for performance optimizations. Using generated values like Math.random()
or Date.now()
is discouraged as it would force a re-render every time and might also provoke bugs if values collide.
Instead, use a unique attribute like an ID or a combination of attributes.
Noncompliant Code Example
function generateButtons(props) {
return props.buttons.map((button, index) => {
<Button key={Math.random()}>{button.number}</Button>
});
}
Compliant Solution
function generateButtons(props) {
return props.buttons.map((button, index) => {
<Button key={button.number}>{button.number}</Button>
});
}
See