Optimizing Change Detection with the Power of Signals

# REACTIVITY

The need for Reactivity

A system's ability to respond to changes in data or state automatically

  • Every FE framework implements its own implementation
  • Zone.js foundational tool in Angular for its implementation of reactivity.
  • We refer to this mechanism traditionally as Change Detection
# CHANGE DETECTION

How Change Detection works

Default Change Detection

There are situations where change detection can become a performance bottleneck

CHANGE DETECTION #

How Change Detection works

OnPush Change Detection

The component itself and its children are checked for changes only when they are marked as "dirty"

  1. One of its Input properties changes
  2. An event is emitted from the component.
  3. The ChangeDetectorRef.markForCheck  function is called manually.
  4. An Observable consumed by an async pipe in the template emits a new value.

When Change Detection is triggered

Zone.js

CHANGE DETECTION #

Monkey patches more than 250 browser APIs

NgZone tracks events from this APIs and schedules an AppRef.tick()

Challenges with Zone.js

A Signal is a wrapper around a value that notifies interested consumers when the value changes.

# Change Detection using Signals

Reactivity using Signals

Signals is the selected new reactivity model

# Change Detection using Signals

The Producer/Consumer Abstraction

Dependency graph

Consumers represent reactive contexts

Producers represent entities that hold a value. Changes are tracked when the producer is accessed within a consumer's reactive context.

# Change Detection using Signals

When the value of the Signal changes

  • View marked with the RefreshView flag.
  • The markAncestorsForTraversal() function is called, marking all ancestors of the View with the HasChildViewsToRefresh flag.

Views act as a consumer

# Change Detection using Signals

async VS signal

# Change Detection using Signals

Targeted and Global mode

Traversal always happens in one of two modes

Global / Targeted 

  1. It will switch to Targeted mode when it encounters an "OnPush + HasChildViewsToRefresh🚩"
  2. Visit components but will not perform change detection for components with the Default strategy or those marked as "Ditry+OnPush".
  3. Perform change detection only for components marked with the RefreshView🚩 flag.
  4. Switch back to Global mode when it reaches an "OnPush + RefreshView🚩" component
# Change Detection using Signals

Targeted and Global mode

# Change Detection using Signals

Targeted and Global mode

Thank You!

Questions?

Bibliography:

 

Copy of Code

By Stefanos Lignos

Copy of Code

  • 140