React clarification

Hello! :wave:

Just a quick question about React:

So I understood the idea of giving keys attribute to elements I loop through, like so:

const arr = [0, 1, 2, 3];

// inside jsx
{arr.map(num => (
<button 
  key={num}
  >
  {num}
</button>
))}

But, what about if I don’t loop through an array? Do I still need a key?

<button key="AC">AC<button/>

Do I still need to do it like this? Or React is fine rendering that without the key? Thank you for your time and effort!

The key is required when you’re [dynamically] generating a list of components, so yup, it’s when you’re looping through some data and rendering based on that.

It’s not required per se: React will log a warning (not an error) if you miss it out. But the reason for that warning is for the (very common) situation where the array of data changes and causes a rerender (rerender just means the component function runs again). So say you have an array

[50, 65, 83]

And you map over it, and render three components.

Then you update that array, and it now looks like

[34, 50, 65, 83]

So the last three items in the array, they haven’t changed and they’re in the same order. So React doesn’t need to rerender those components. But it needs a way to know that, and that’s what the key is for. Using keys, the new element (34, at the start) will render, the other three will not rerender.

This is also why using the index (eg arr.map((item, index) => <p key={index) as a key doesn’t work – if the components use the index, then when map runs again on that array after an item has been added anywhere except the end, the keys will change and all the components will rerender.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.