DEV Community

JayZho
JayZho

Posted on • Edited on

Working with Arrays in React (updating)

Mapping to a list of components

Say we got an array of fruits, and we'd like to render each as a fruit card in the page, then we can use .map as below:

let fruits = ["apple", "banana", "peach"]
return (
  { fruits.map(x => <FruitCard name={x}>) }
)
Enter fullscreen mode Exit fullscreen mode

But React may warn you that "Each child in a list should have a unique "key" prop". And the reason is as follow:

Say we initially had a list of fruits as ["apple", "banana"], and we mapped and rendered them as 2 individual <FruitCard> components in the page.

Later on, when we need to add one more fruit "peach" and update the page to display this third <FruitCard>, without the "key" prop, React actually has no idea about which fruits are newly added/deleted or which have stayed unchanged, hence it has no choice but to remove the previous 2 elements from the DOM tree and create a new element for each child of the updated list and add them to the DOM tree all over again.

To avoid this inefficient DOM update, React requires us to give each child a unique ID, then later when the list is updated, React only updates the ones that are changed according to their ID. In the example above, we could do something like: (assuming each fruit has its unique name)

return (
  { fruits.map(x => <FruitCard name={x} key={x}>) }
)
Enter fullscreen mode Exit fullscreen mode

In this way, when "peach" is added, React knows that "apple" and "banana" were the old elements that are untouched, hence it only adds a new element for "peach" into the DOM tree, saving the work to remove and re-add the other 2 old elements.

In short, the "key" prop is to allow React to keep track of the list elements, therefore improving the performance on re-rendering.

Top comments (0)