React Performance
Loops with Ionic Components
When using loops with Ionic components, we recommend using React'skey attribute. This allows React to re-render loop elements in an efficient way by only updating the content inside of the component rather than re-creating the component altogether.
By usingkey you can provide a stable identity for each loop element so React can track insertions and deletions within the iterator. Below is an example of how to usekey:
MyComponent.tsx
importReact,{ useState}from'react';
import{IonContent,IonItem,IonLabel,IonPage}from'@ionic/react';
exportconstMyComponent:React.FC=()=>{
const[items, setItems]=useState([{ id:0, value:'Item 0'},{ id:1, value:'Item 1'},...]);
return(
<IonPage>
<IonContent>
{items.map(item=>{
return(
<IonItemkey={item.id}>
<IonLabel>{item.value}</IonLabel>
</IonItem>
)
})}
</IonContent>
</IonPage>
)
}
In this example, we have an array of objects calleditems. Each object contains avalue and anid. Using thekey attribute, we pass theitem.id for each object. Thisid is used to provide a stable identity for each loop element.
For more information on how React renders lists usingkey see:https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key