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>
}
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 :)
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
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.
No, you only need it for the outer component (Parent). Documentation
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