0
0
Angularframework~15 mins

When to use OnPush in Angular - Deep Dive

Choose your learning style9 modes available
Overview - When to use OnPush
What is it?
OnPush is a change detection strategy in Angular that tells the framework to check a component's view only when its input properties change or when an event happens inside it. Instead of checking every component all the time, Angular checks only when it really needs to. This helps make apps faster and more efficient by reducing unnecessary work.
Why it matters
Without OnPush, Angular checks every component on every change, which can slow down apps, especially big ones. OnPush helps apps run smoothly by skipping checks when nothing relevant has changed. This means users get faster responses and better experiences, especially on slower devices or complex apps.
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 performance optimization techniques and reactive programming with RxJS in Angular.
Mental Model
Core Idea
OnPush tells Angular to check a component only when its inputs change or it triggers an event, skipping unnecessary checks to boost performance.
Think of it like...
Imagine a security guard who only checks rooms when someone rings the doorbell or leaves a note, instead of checking every room all the time. This saves time and effort while still catching important changes.
┌───────────────┐       ┌───────────────┐
│ Default Check │──────▶│ Checks all    │
│ Strategy      │       │ components    │
└───────────────┘       └───────────────┘
         ▲                      ▲
         │                      │
┌───────────────┐       ┌───────────────┐
│ OnPush Check  │──────▶│ Checks only   │
│ Strategy      │       │ when inputs   │
└───────────────┘       │ change or     │
                        │ events occur  │
                        └───────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Angular Change Detection
🤔
Concept: Learn how Angular normally checks for changes in components.
Angular automatically checks every component's data to see if it changed and updates the screen. This happens after events like clicks or timers. This process is called change detection and runs frequently to keep the UI up to date.
Result
Angular updates the UI whenever it detects changes anywhere in the app.
Knowing how Angular checks for changes helps you understand why sometimes apps slow down when they have many components.
2
FoundationWhat is OnPush Change Detection?
🤔
Concept: OnPush changes when Angular checks a component by limiting checks to specific triggers.
With OnPush, Angular only checks a component when its input properties change by reference, or when an event happens inside it. It skips checking if nothing relevant changed, saving time.
Result
Components with OnPush run fewer checks, improving app speed.
Understanding OnPush shows how you can control Angular's checking to make apps faster.
3
IntermediateHow Input Changes Trigger OnPush Checks
🤔Before reading on: Do you think OnPush detects changes if an input object's content changes but its reference stays the same? Commit to yes or no.
Concept: OnPush relies on input property references changing, not deep content changes.
OnPush checks inputs by comparing their references (memory addresses). If you change a property inside an object but keep the same object, Angular won't detect it. You must replace the whole object with a new one to trigger a check.
Result
Only new object references cause OnPush to update the component.
Knowing that OnPush uses reference checks helps avoid bugs where UI doesn't update because the object itself didn't change.
4
IntermediateEvents and Observables Triggering OnPush
🤔Before reading on: Can OnPush detect changes from user clicks inside the component even if inputs don't change? Commit to yes or no.
Concept: OnPush also runs checks when events or observable data inside the component emit new values.
If a user clicks a button or an observable inside the component emits a new value, OnPush triggers change detection for that component. This means internal events still update the UI even if inputs stay the same.
Result
User interactions and observable updates keep the UI responsive with OnPush.
Understanding event triggers ensures you know when OnPush components update without input changes.
5
AdvancedWhen to Prefer OnPush Strategy
🤔Before reading on: Do you think OnPush is best for all components or only some? Commit to your answer.
Concept: OnPush is ideal for components with immutable inputs and predictable change triggers.
Use OnPush when your component inputs are immutable (never changed inside the component) and when you want to optimize performance. It works well with reactive programming where data streams emit new values. Avoid OnPush if your component relies on mutable objects or external changes without events.
Result
OnPush improves performance in well-structured, immutable data apps.
Knowing when to use OnPush helps balance performance gains with development complexity.
6
ExpertCommon Pitfalls and Debugging OnPush Components
🤔Before reading on: Do you think OnPush can cause UI not to update if you mutate objects instead of replacing them? Commit to yes or no.
Concept: OnPush can cause silent UI bugs if mutable data is changed without changing references.
If you mutate an input object without changing its reference, OnPush won't detect the change, so the UI stays stale. Debugging requires checking if inputs are replaced properly. Tools like Angular DevTools help inspect change detection cycles and component states.
Result
Understanding this prevents subtle bugs and improves debugging skills.
Recognizing OnPush's reliance on immutable data prevents common silent update bugs in production.
Under the Hood
Angular's change detection walks the component tree to check for changes. With default strategy, it checks every component on every event. OnPush changes this by marking components as 'dirty' only when input references change or events occur inside. Angular skips checking OnPush components unless marked dirty, reducing work.
Why designed this way?
OnPush was designed to improve performance by avoiding unnecessary checks. Early Angular versions checked everything, causing slowdowns in big apps. OnPush leverages immutable data patterns and event triggers to minimize checks while keeping UI consistent.
┌───────────────┐
│ Event Occurs  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Change Detection│
│ Starts        │
└──────┬────────┘
       │
       ▼
┌───────────────┐       ┌───────────────┐
│ Default       │──────▶│ Check all     │
│ Strategy      │       │ components    │
└───────────────┘       └───────────────┘
       │
       │
       ▼
┌───────────────┐       ┌───────────────┐
│ OnPush        │──────▶│ Check only if │
│ Strategy      │       │ inputs/events │
└───────────────┘       └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does OnPush detect changes if you modify a property inside an input object without changing the object itself? 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 if its internal properties mutate.
Why it matters:Believing this causes UI to not update when objects are mutated, leading to confusing bugs.
Quick: Can OnPush components update their view when an event inside them happens even if inputs don't change? Commit to yes or no.
Common Belief:OnPush components only update when inputs change, never from internal events.
Tap to reveal reality
Reality:OnPush also triggers change detection on internal events like clicks or observable emissions.
Why it matters:Misunderstanding this limits how you design interactive components with OnPush.
Quick: Is OnPush always better for performance regardless of app size? Commit to yes or no.
Common Belief:OnPush should be used everywhere to make apps faster.
Tap to reveal reality
Reality:OnPush helps mainly in large apps with immutable data; in small apps or mutable data, it can add complexity without benefit.
Why it matters:Using OnPush everywhere can make code harder to maintain without real speed gains.
Quick: Does Angular automatically detect changes from asynchronous operations in OnPush components? Commit to yes or no.
Common Belief:Angular always detects async changes in OnPush components without extra work.
Tap to reveal reality
Reality:Async changes must trigger events or observable emissions to update OnPush components; otherwise, UI won't refresh.
Why it matters:Ignoring this causes stale UI when async data changes silently.
Expert Zone
1
OnPush works best with immutable data patterns; mixing mutable and immutable data can cause subtle bugs.
2
Using OnPush with observables and the async pipe ensures automatic UI updates without manual change detection calls.
3
Manually triggering change detection (e.g., ChangeDetectorRef.markForCheck) is sometimes needed when external data changes without input reference updates.
When NOT to use
Avoid OnPush if your component relies heavily on mutable objects or external services that update data without emitting events. In such cases, default change detection or manual detection control is safer.
Production Patterns
In large Angular apps, OnPush is used with smart container components passing immutable inputs to dumb presentational components. This pattern reduces checks and improves performance. Developers combine OnPush with RxJS observables and async pipes for reactive UI updates.
Connections
Immutable Data Structures
OnPush relies on immutable data to detect changes efficiently.
Understanding immutable data helps grasp why OnPush checks input references instead of deep content.
Reactive Programming with RxJS
OnPush works well with reactive streams that emit new values to trigger UI updates.
Knowing reactive programming clarifies how OnPush components stay updated without manual checks.
Event-Driven Systems (Computer Science)
OnPush triggers updates based on events, similar to event-driven architectures reacting only to changes.
Recognizing OnPush as an event-driven pattern helps understand its efficiency and when it applies.
Common Pitfalls
#1Mutating input objects without changing their reference causes UI not to update.
Wrong approach:this.inputData.name = 'New Name'; // inputData reference unchanged
Correct approach:this.inputData = {...this.inputData, name: 'New Name'}; // new object reference
Root cause:OnPush detects changes by input reference, not internal mutations.
#2Expecting OnPush to detect changes from async operations without triggering events.
Wrong approach:setTimeout(() => { this.data = newData; }, 1000); // no event or observable
Correct approach:Use observables or call ChangeDetectorRef.markForCheck() after async update.
Root cause:OnPush requires explicit triggers to run change detection.
#3Using OnPush on components with mutable inputs and no event triggers leads to stale UI.
Wrong approach:@Input() data; // mutable object // data mutated internally without new reference or events
Correct approach:Use default change detection or ensure inputs are immutable and replaced on change.
Root cause:OnPush depends on immutable inputs and event triggers to detect changes.
Key Takeaways
OnPush is a powerful Angular strategy that improves performance by limiting when components update.
It works by checking components only when input references change or internal events occur.
Using immutable data and reactive patterns is key to making OnPush work correctly.
Misusing OnPush with mutable data or missing event triggers causes UI bugs and stale views.
Understanding OnPush helps build faster, more efficient Angular apps with predictable updates.