When rendering lists with the ngFor directive, you can often notice performance degradation if the underlying data changes frequently. If you need to mutate part of the displayed data after a user action, Angular will by default re-render the entire list. This can become a bottleneck, particularly for larger collections.

By providing a trackBy function, you can help Angular identify which items are newly added and which ones already exist. This enables the framework to reuse existing DOM elements and avoid unnecessary re-renders of unchanged items.

Let’s look at a practical example. The full code is available on GitHub and Stackblitz.

In this demo, we have a list rendered with ngFor, alongside a button that appends a new item to the list.

image

The corresponding template and component code are shown below.

<div>
  <ul>
    <li *ngFor="let item of items; "> {{item.name}} </li>
  </ul>
</div>

<input type="button" value="Add Angular" (click)="addItem()">
export class AppComponent {
  title = 'trackby-example';
  items: Item[] = [
    { id: 1, name: 'HTML' },
    { id: 2, name: 'CSS' },
    { id: 3, name: 'JavaScript' },
  ];
  addItem() {
    this.items = [
      { id: 1, name: 'HTML' },
      { id: 2, name: 'CSS' },
      { id: 3, name: 'JavaScript' },
      { id: 4, name: 'Angular' },
    ];
  }
}

If you open the Chrome developer tools and click the "Add" button, you’ll notice in the elements panel that the entire list gets highlighted. This indicates that Angular is re-rendering every row in the list, as seen in the screenshot below.

image

Now, let’s add a trackBy function and observe how the behavior changes.

The updated HTML template looks like this:

 <li *ngFor="let item of items;trackBy:trackBy "> {{item.name}} </li>

And the corresponding TypeScript function is:

trackBy(index: number, item: Item) {
    return item.id;
  }
```


So if you see here we are returning id in the trackBy function, which is something unique to the object in the array which helps Angular understand the uniqueness of each object in our case.
If you now relaunch the application and do the same activity you will be able to see that only a new object line is added without rerendering the old objects.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7qizx4hefxen0zwxcon.png)

Hope you were able to understand the concept of using trackBy and how it can help improve performance.
If you liked it please share it with your friends or if any suggestions reach me out on [Twitter](https://twitter.com/nikhild64) or comment below.
Till next time Happy Learning!