How trackBy Improves Performance in Angular?

September 21, 2024 8:45 PM

Angular @for ngFor trackBy function

The trackBy function in Angular improves performance and minimizes DOM manipulations by providing a way for Angular to uniquely identify each item in a list. This allows Angular to efficiently update only the items that have changed, rather than re-rendering the entire list. Here's how it works:


How trackBy Improves Performance


  1. Unique Identification: By using a unique identifier for each item, Angular can keep track of which items have been added, removed, or moved. This is done through the trackBy function, which returns a unique key for each item.

  2. Efficient DOM Updates: When the list changes, Angular uses the unique keys to determine which items need to be updated. Instead of re-rendering the entire list, Angular only updates the specific items that have changed. This reduces the number of DOM manipulations, which can be expensive in terms of performance.

  3. State Preservation: If the list items contain stateful elements (like form inputs), using a unique key ensures that the state is preserved correctly when the list is updated. Without trackBy, Angular might recreate the entire list, losing the state of each item.


In example, we have two ways of rendering the list

Using @for with track

<ul>
  @for (ingredient of ingredientList; track ingredient.name) {
  <li>{{ingredient.name}} {{ingredient.quantity}}</li>
  }
</ul>

Using *ngFor with trackBy:

<ul>
  <li *ngFor="letingredient of ingredientList; indexasi; trackBy: trackByFn">
    {{ingredient.name}} {{ingredient.quantity}}
  </li>
</ul>


trackBy Function


trackByFn(index: number, ingredient: any): string {
  return ingredient.name;
}

How It Works?


  1. Initial Render: When the list is first rendered, Angular creates DOM elements for each item in the list.
  2. List Update: If the list changes (e.g., an item is added, removed, or reordered), Angular uses the trackBy function to determine which items have changed.
  3. Efficient Update: Angular updates only the DOM elements that correspond to the changed items, rather than re-rendering the entire list. This minimizes the number of DOM manipulations and improves performance.


Summary

  • Without trackBy: Angular re-renders the entire list whenever it changes, leading to more DOM manipulations and potential performance issues.
  • With trackBy: Angular uses the unique keys to update only the changed items, reducing the number of DOM manipulations and improving performance.


By using the trackBy function, you ensure that Angular handles dynamic lists efficiently, preserving the state of each item and minimizing unnecessary DOM updates.

Comments


    Read next