BP177: Use the OnPush change detection strategy with immutable data structures

The OnPush change detection strategy is a performance optimization technique in Angular that reduces the number of times Angular checks for changes in the component tree. By default, Angular uses the default change detection strategy, which checks for changes in all components and their children every time a user event or asynchronous operation occurs. This can lead to performance issues, especially in large applications with complex component trees.

Immutable data structures are data structures that cannot be changed once they are created. This means that any changes to the data must create a new copy of the data structure. Immutable data structures are useful in Angular because they allow for more efficient change detection. When a change is made to an immutable data structure, Angular can quickly determine if the data has changed by comparing the reference to the old data structure with the reference to the new data structure. This is much faster than checking each property of the data structure for changes.

Here is an example of how to use the OnPush change detection strategy with immutable data structures:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
  data: ReadonlyArray<string> = ['one', 'two', 'three'];

  addItem(item: string) {
    this.data = [...this.data, item];
  }
}
In this example, the component uses the OnPush change detection strategy by setting the changeDetection property to ChangeDetectionStrategy.OnPush. The data property is an immutable data structure created using the ReadonlyArray type. When the addItem method is called, it creates a new copy of the data structure using the spread operator. This triggers change detection in the component and updates the view with the new data.

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

Get it on Google Play