I have a list of items that doesn't contain enough data to generate a unique key. If I use the uuid library to generate an ID, will a single item change also causes the other items to re-render since their key will change each time?
const people = [
{
gender: 'male',
firstName: 'david',
},
{
gender: 'male',
firstName: 'david',
},
{
gender: 'male',
firstName: 'joe',
},
]
const renderPeople = () => {
return people.map(person => {
return (
<div key={uuid.v4() /* a new value each time? */ }>
<p>{person.gender}</p>
<p>{person.firstName}</p>
</div>
)
})
}
some time later... one of the davids changed
const people = [
{
gender: 'male',
firstName: 'david',
},
{
gender: 'male',
firstName: 'davidzz',
},
{
gender: 'male',
firstName: 'joe',
},
]
As a solution, you can use React Fragments to wrap the components, and it will reduce the load on the DOM, resulting in faster rendering times and decreased memory usage. In this article, I have discussed 5 different methods to prevent unnecessary re-rendering in React components.
If each list element has a consistent key, React can avoid re-rendering components even when list items are added or removed. Without the key on <ListItem> we're getting a Warning: Each child in a list should have a unique "key" prop message.
It can be easily avoided by either extending your class-based components from React.PureComponent, utilising the shouldComponentUpdate life-cycle hook or wrapping your components in a React.memo Higher-Order Component. 2. Use Functional Component instead of Class
If the key is not linked to the data in some way, react cannot do any optimisation. 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.
<div key={uuid.v4()}>
assigns new key for each <div>
every time, so it is useless.
If the array stays same, UUID should be generated on array creation.
If the array changes, e.g. received from HTTP request, UUIDs for elements with same content will be generated again.
In order to avoid that, key
should be specific to person
entity. It's always preferable to use internal identifiers (database IDs) where available for unambiguity.
If identifiers are not available, key
may depend on element contents:
return (
<div key={JSON.stringify(person)}>
<p>{person.gender}</p>
<p>{person.firstName}</p>
</div>
)
It's more efficient to hash elements once at the time when an array is created, e.g. with uuid
:
import uuidv3 from 'uuid/v3';
...
for (const person of people) {
person.key = uuidv3(JSON.stringify(person), uuidv3.URL);
}
Or use dedicated hashing function like object-hash
.
Notice that hashing may result in key collisions if there are elements with same contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With