Change detections rules in angular

imm9o

Islam Muhammad

Posted on January 2, 2021

Change detections rules in angular
![alt](https://images.unsplash.com/reserve/81gZijLSWfge41LgzqQ6_Moving%20Parts.JPG?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1352&q=80) Photo by Chester Alvarez on Unsplash

What makes angular running change detection and how to optimize it

What is change detection?

Change detection is the mechanism designed to track changes in an application state and render the updated state on the screen. It ensures that the user interface always stays in sync with the internal state of the program.

How change detections work in angular?

Angular uses ZoneJS to intercept events that occurred in the application and run a change detection cycle automatically.

We can reduce events that angular intercept by changing ChangeDetectionStrategy in component decorator to ChangeDetectionStrategy.OnPush

ChangeDetectionStrategy.OnPush tells Angular that the component only depends on its @inputs() ( aka pure ) and needs to be checked only in the following cases:

1️⃣ The Input reference changes.
2️⃣ An event originated from the component or one of its children. ( The rule applies only to DOM events)
3️⃣ We run change detection explicitly.
4️⃣ Observable emits a new value inside the component template.

How to optimize running of change detection

  • Always use OnPush Change Detection Strategy.
  • Always use immutable data because once you set component to OnPush strategy angular will use shallow comparison to detect change and perform the reRender task.
  • Prevent unnecessary emits in observables inside component.
  • Prevent triggers unnecessary async task like scrolling using technics like Debounce or Throttle.
  • Reduce the number of long tasks by moving it to Web Workers.
  • Use runOutsideAngular when starting a work consisting of one or more asynchronous tasks that don't require UI.
💖 💪 🙅 🚩
imm9o
Islam Muhammad

Posted on January 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related