Photo by Ross Findon 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 amount 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.