0
0
Angularframework~15 mins

OnPush change detection strategy in Angular - Deep Dive

Choose your learning style9 modes available
Overview - OnPush change detection strategy
What is it?
OnPush change detection strategy is a way Angular decides when to update a component's view. Instead of checking for changes all the time, it only checks when specific inputs change or events happen. This makes apps faster by reducing unnecessary work. It is a setting you apply to components to control how Angular tracks changes.
Why it matters
Without OnPush, Angular checks every component on every event, which can slow down apps as they grow. OnPush helps apps run smoothly by only updating when really needed. This saves battery on phones and makes websites feel quicker. It solves the problem of wasted work and lag in user interfaces.
Where it fits
Before learning OnPush, you should understand Angular components, data binding, and the default change detection process. After mastering OnPush, you can explore advanced state management and performance optimization techniques in Angular.
Mental Model
Core Idea
OnPush tells Angular to check a component only when its inputs change or an event inside it happens, skipping unnecessary checks.
Think of it like...
Imagine a security guard who only checks a room when someone rings the doorbell or brings a package, instead of checking every room all the time.
┌─────────────────────────────┐
│ Angular Component            │
│                             │
│  Inputs changed? ──► Check view update
│  Event inside? ──────► Check view update
│  Otherwise ──────────► Skip check
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Angular Change Detection
🤔
Concept: Angular automatically updates the screen when data changes using a process called change detection.
Angular runs change detection after events like clicks or HTTP responses. It checks all components to see if their data changed and updates the view accordingly.
Result
The screen always shows the latest data but Angular may do more work than needed.
Understanding the default change detection is key to seeing why OnPush can improve performance.
2
FoundationWhat Triggers Default Change Detection
🤔
Concept: Default change detection runs after many events, including user actions and timers.
Every time something happens, Angular checks every component from top to bottom to see if it needs to update the view.
Result
Even components with no changes get checked, which can slow down big apps.
Knowing what triggers checks helps understand how OnPush reduces unnecessary work.
3
IntermediateHow OnPush Changes Detection Behavior
🤔Before reading on: Do you think OnPush checks components more often, less often, or the same as default? Commit to your answer.
Concept: OnPush tells Angular to check a component only when its input properties change or an event happens inside it.
When a component uses OnPush, Angular skips checking it unless: - An input property changes by reference - An event originated inside the component - You manually trigger change detection This reduces the number of checks Angular performs.
Result
Components with OnPush update less often, improving app speed.
Understanding OnPush's selective checking is crucial for optimizing Angular apps.
4
IntermediateInput Property Change Detection with OnPush
🤔Before reading on: Does OnPush detect changes if an input object's internal data changes but its reference stays the same? Commit to your answer.
Concept: OnPush relies on input property references changing, not internal mutations.
If an input is an object and you change a property inside it without changing the object itself, OnPush will NOT detect this change. You must replace the object with a new one to trigger detection.
Result
Only new object references cause OnPush to update the component view.
Knowing this prevents bugs where UI doesn't update because of mutable data changes.
5
IntermediateEvents and Manual Triggers with OnPush
🤔
Concept: OnPush also updates when events happen inside the component or when manually triggered.
User actions like clicks inside the component trigger change detection even if inputs don't change. Developers can also call methods like markForCheck() to force updates.
Result
OnPush components stay responsive to user interaction and manual updates.
Recognizing these triggers helps balance performance with UI responsiveness.
6
AdvancedCombining OnPush with Immutable Data Patterns
🤔Before reading on: Do you think using mutable or immutable data works better with OnPush? Commit to your answer.
Concept: OnPush works best with immutable data, where new objects replace old ones instead of changing them.
Immutable data means every change creates a new object. This fits OnPush's need for new references to detect changes. Libraries like NgRx use this pattern to optimize Angular apps.
Result
Using immutable data with OnPush leads to predictable and efficient UI updates.
Understanding this synergy is key to mastering Angular performance.
7
ExpertCommon Pitfalls and Debugging OnPush Components
🤔Before reading on: Can OnPush cause a component to not update even when data changes? Commit to your answer.
Concept: OnPush can cause UI not to update if data changes are not done by replacing references or if change detection is not triggered properly.
Developers often forget to replace objects or call detectChanges(). This leads to stale views. Debugging requires checking input references and event triggers carefully.
Result
Knowing these pitfalls helps avoid subtle bugs and improves app reliability.
Recognizing OnPush's limits prevents frustrating UI bugs in production.
Under the Hood
Angular uses a tree of components and runs change detection by traversing this tree. With OnPush, Angular marks components as 'check only if inputs changed or events fired'. It compares input references using strict equality. If unchanged, Angular skips checking that component's template. This reduces CPU cycles and DOM updates.
Why designed this way?
OnPush was designed to improve performance by avoiding unnecessary checks in large apps. The default strategy is simple but inefficient for big component trees. OnPush leverages immutable data patterns and event-driven updates to minimize work while keeping UI consistent.
┌───────────────┐       ┌───────────────┐
│ Parent Comp   │──────▶│ Child Comp    │
│ (Default)     │       │ (OnPush)      │
└───────────────┘       └───────────────┘
       │                      │
       │ Input reference changed?
       │ Yes ──────────────▶ Check and update
       │ No ───────────────▶ Skip check
       │ Event inside comp?
       │ Yes ──────────────▶ Check and update
       │ No ───────────────▶ Skip check
Myth Busters - 4 Common Misconceptions
Quick: Does OnPush detect changes when you modify a property inside an input object without changing its reference? Commit to yes or no.
Common Belief:OnPush detects all changes inside input objects automatically.
Tap to reveal reality
Reality:OnPush only detects changes if the input object's reference changes, not internal mutations.
Why it matters:Believing this causes bugs where the UI does not update because Angular thinks nothing changed.
Quick: Does OnPush mean Angular never checks the component again after first render? Commit to yes or no.
Common Belief:OnPush disables change detection completely for the component.
Tap to reveal reality
Reality:OnPush only limits checks to specific triggers; events and manual calls still cause updates.
Why it matters:Thinking OnPush disables updates leads to confusion and broken UI.
Quick: Is OnPush always faster than default change detection? Commit to yes or no.
Common Belief:OnPush always improves performance no matter what.
Tap to reveal reality
Reality:OnPush can add complexity and overhead if used incorrectly or with mutable data.
Why it matters:Misusing OnPush can cause worse performance and harder debugging.
Quick: Can OnPush cause a component to update even if inputs don't change? Commit to yes or no.
Common Belief:OnPush only updates when inputs change.
Tap to reveal reality
Reality:Events inside the component or manual triggers can also cause updates with OnPush.
Why it matters:Ignoring event triggers leads to misunderstanding component behavior.
Expert Zone
1
OnPush works best with immutable data but can be combined with manual change detection calls for mutable data scenarios.
2
Angular's internal change detection uses a 'dirty checking' mechanism that OnPush optimizes by skipping subtrees, but this requires careful input management.
3
Using OnPush with async pipes and observables can further optimize performance by reducing manual change detection triggers.
When NOT to use
Avoid OnPush if your app heavily relies on mutable shared state without immutable patterns or if you cannot guarantee input reference changes. In such cases, default change detection or manual change detection control might be better.
Production Patterns
In real apps, OnPush is combined with state management libraries like NgRx or Akita that enforce immutability. Developers use OnPush to optimize large component trees and rely on async pipes to handle observable data streams efficiently.
Connections
Immutable Data Structures
OnPush builds on the idea of immutable data to detect changes efficiently.
Understanding immutable data helps grasp why OnPush relies on reference changes to trigger updates.
Event-Driven Programming
OnPush triggers updates on internal events, linking it to event-driven design.
Knowing event-driven principles clarifies how user actions cause UI updates even with OnPush.
Selective Rendering in Video Games
Both OnPush and selective rendering optimize performance by updating only changed parts.
Recognizing this cross-domain pattern shows how efficient updates improve user experience in different fields.
Common Pitfalls
#1UI does not update after changing a property inside an input object.
Wrong approach:this.inputObject.property = newValue; // OnPush component does not update
Correct approach:this.inputObject = {...this.inputObject, property: newValue}; // New reference triggers update
Root cause:Misunderstanding that OnPush detects changes by object reference, not internal mutations.
#2Expecting OnPush component to update without any input or event changes.
Wrong approach:No input changes or events, but expecting UI refresh automatically.
Correct approach:Call ChangeDetectorRef.markForCheck() or detectChanges() to manually trigger update.
Root cause:Not realizing OnPush limits automatic checks to specific triggers.
#3Using OnPush without immutable data leads to stale UI.
Wrong approach:Mutating shared objects passed as inputs without changing references.
Correct approach:Use immutable patterns or replace objects to ensure OnPush detects changes.
Root cause:Ignoring the need for new references with OnPush strategy.
Key Takeaways
OnPush change detection improves Angular app performance by checking components only when inputs change or events occur.
It relies on input property references changing, so immutable data patterns work best with OnPush.
Events inside the component and manual triggers also cause OnPush components to update.
Misusing OnPush by mutating objects without changing references causes UI bugs.
Understanding OnPush helps build faster, more efficient Angular applications.