BP160: Use OnPush change detection strategy to reduce unnecessary change detection cycles

Use OnPush change detection strategy to reduce unnecessary change detection cycles. Angular uses change detection to detect changes in the component's data and update the view accordingly. By default, Angular uses the default change detection strategy, which checks for changes in all components and their children on every tick of the JavaScript event loop. This can lead to performance issues when the application has a large number of components or when the data changes frequently.

OnPush change detection strategy is an alternative change detection strategy that can be used to optimize performance. With OnPush, Angular only checks for changes in a component when one of its input properties changes or when an event is triggered within the component. This can significantly reduce the number of unnecessary change detection cycles and improve the performance of the application.

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
  @Input() data: any;
  
  handleClick() {
    // do something
  }
}

In the above example, the OnPush change detection strategy is set for the ExampleComponent. This means that Angular will only check for changes in the component when the data input property changes or when the handleClick method is called. This can improve the performance of the component and the application as a whole.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play