Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested key property requirements in React

I understand when using arrays of Components the key property is assumed to be the index of the array, and should be explicitly set. Are the children of those children recommended to be explicitly set?

{arr.map(item, i) => {
  <Parent
    key={item.ID}
  >
    <Child
      key={`child${item.ID`}   //required to ensure correct reconciliation?
    />
  </Parent>
}
like image 343
sammarcow Avatar asked Jun 05 '19 18:06

sammarcow


4 Answers

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity (source)

The general purpose of a key is to optimize React's rendering performance. If you have a list of items, giving a key tells React how to remember this item for subsequent renders. If you use an array index, that can defeat the purpose of the key (if the order of those elements change). Its better to use a unique ID or something more specific to the entity being rendered.

With that context, The parent element is what needs the key, so React can do its optimizations. The children of that "dynamic" element are attached to that parent / its key so there's no need to apply a key on the children`. Just the parents that are rendered in a loop :)

like image 143
John Ruddell Avatar answered Sep 18 '22 16:09

John Ruddell


only the outermost items you iterate you need to set a key on. As far as I see there's a single child component per Parent, so no need to worry abot key in this case

like image 44
Uma Avatar answered Sep 19 '22 16:09

Uma


You do not need to explicitly set keys on the children.

The follow is a good article on using keys: https://reactjs.org/docs/lists-and-keys.html

It explicitly recommends not using indexes as keys for an array:

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

like image 22
hwaring Avatar answered Sep 19 '22 16:09

hwaring


No, you only need it for the outer component (Parent). Documentation

like image 40
Peter Cheng Avatar answered Sep 18 '22 16:09

Peter Cheng