0
0
Angularframework~8 mins

TrackBy in ngFor in Angular - Performance & Optimization

Choose your learning style9 modes available
Performance: TrackBy in ngFor
HIGH IMPACT
This affects how Angular updates the DOM when rendering lists, improving rendering speed and reducing layout shifts.
Rendering a list with ngFor and updating items frequently
Angular
<div *ngFor="let item of items; trackBy: trackById">{{item.name}}</div>

trackById(index: number, item: any) {
  return item.id;
}
Angular reuses existing DOM elements by tracking items with unique IDs, minimizing DOM changes.
📈 Performance Gainsingle reflow per changed item, significantly fewer reflows overall
Rendering a list with ngFor and updating items frequently
Angular
<div *ngFor="let item of items">{{item.name}}</div>
Angular recreates all DOM elements on each update, causing many reflows and layout shifts.
📉 Performance Costtriggers N reflows per update where N is the number of items
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
ngFor without trackByRemoves and recreates all nodes on updateN reflows per update (N = list length)High paint cost due to full node replacement[X] Bad
ngFor with trackByReuses existing nodes, updates only changed itemsReflows only for changed itemsLower paint cost due to minimal DOM changes[OK] Good
Rendering Pipeline
When Angular updates a list, it compares new and old items. Without trackBy, it destroys and recreates DOM nodes, triggering layout recalculations and repaints. With trackBy, Angular matches items by ID, reusing DOM nodes and reducing layout thrashing.
Layout
Paint
Composite
⚠️ BottleneckLayout due to DOM node removal and insertion
Core Web Vital Affected
CLS
This affects how Angular updates the DOM when rendering lists, improving rendering speed and reducing layout shifts.
Optimization Tips
1Always use trackBy with ngFor when rendering lists that update frequently.
2Use a unique identifier like an ID in the trackBy function for best results.
3Avoid recreating DOM nodes unnecessarily to reduce layout shifts and improve CLS.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using trackBy in ngFor?
AIt reduces unnecessary DOM node creation and destruction.
BIt increases the bundle size slightly.
CIt delays rendering until all data is loaded.
DIt automatically sorts the list items.
DevTools: Performance
How to check: Record a performance profile while updating the list. Look for layout and paint events related to the list container.
What to look for: Fewer layout recalculations and shorter paint times indicate good use of trackBy.