DEV Community

Cover image for Improve *ngFor performance with trackBy
Maciej Modzelewski
Maciej Modzelewski

Posted on • Originally published at


Improve *ngFor performance with trackBy

Whenever you are using *ngFor in your Angular application consider setting trackBy function for it.

By default, Angular uses reference comparison for objects in the list. This might not be the optimal approach, especially when you update your list's data from the server.

Instead, you could be using some unique and stable identifier that your objects have. Thanks to comparing by the id, Angular won't need to rerender all elements every time you fetch an updated list from the server (object references will be changed but ids won't).

Less computations -> performance gain!

How to use the trackBy then?

You need to create a function that matches TrackByFunction interface.

interface TrackByFunction<T> {
  (index: number, item: T): any;

// might be something like this
function trackByTransaction(index: number, item: Transaction): string {
Enter fullscreen mode Exit fullscreen mode

And use it in the template:

<div *ngFor="let transaction of transactions; trackBy: trackByTransaction">
  <!--  transaction view  -->
Enter fullscreen mode Exit fullscreen mode

That's it! Now go and optimise your lists :)

Happy coding! 😀

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.