The Mental Model Behind Angular Signals: signal(), computed(), and effect()
Core Signals: Build self-updating UIs using signal() for base state, computed() for derived values, and effect() for side effects.
For years, Angular relied on Zone.js for change detection. Zone.js monkey-patched browser APIs (setTimeout, Promise, DOM events) so it could notify Angular whenever async work occurred. Angular would then run a top-to-bottom dirty check across the entire component tree.
While simple conceptually, this coarse-grained model caused unnecessary checks and performance headaches in large applications.
Angular Signals introduce fine-grained, push-pull reactivity. Instead of guessing when something might have changed, Angular tracks dependencies at the property level and updates only the specific DOM bindings that depend on that data.
The system is built on three core primitives:
- **signal():** Writable reactive state.
- **computed():** Pure derived state with automatic memoization.
- **effect():** Side-effect operations triggered by reactive dependencies.
## 1. Push-Pull Reactivity
Signals use a two-phase push-pull design to stay fast and avoid redundant calculations:
```text
[ Writable Signal ] ──(1. Push dirty flag)──> [ Dependent Consumers ]
│
(2. Pull fresh value when read/rendered)
▼
[ Precise DOM Update ]
```
- **Push Phase:** When a signal's value changes, it marks dependent computed() nodes and template bindings as "dirty" (stale). It does not evaluate calculations immediately.
- **Pull Phase:** When the view engine needs to render the screen, it requests the value. The signal checks whether it is marked dirty; if so, it recalculates and caches the result. If no template or code reads the value, the calculation never runs.
## 2. Writable Signals: signal()
A writable signal holds state you can update directly.
### 2.1 Reading and Declaring State
Invoke the signal with parentheses () to read its current value:
```ts
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
)
count = signal(0);
// Object signal (WritableSignal<{ name: string; isActive: boolean }>)
user = signal({ name: 'Rahul', isActive: true });
}
```
### 2.2 Updating Values
Writable signals offer two primary methods to change state:
- .set(newValue)
Replaces the state directly with a new value:
```ts
this.count.set(10);
this.user.set({ name: 'Priya', isActive: false });
.update(fn)
```
Derives the next value based on the previous state:
```ts
// Increment count
this.count.update(current => current + 1);
// Update a property immutably
this.user.update(u => ({ ...u, isActive: !u.isActive }));
```
### 2.3 Custom Equality Checks
By default, signals compare values using strict identity (===). If you set an identical value, change notifications are suppressed. You can supply a custom equality function for deep comparisons or specific equality checks:
```ts
interface Coordinates {
x: number;
y: number;
}
// Prevents dirty notifications if x and y match
coords = signal(
{ x: 10, y: 20 },
{ equal: (prev, next) => prev.x === next.x && prev.y === next.y }
);
```
## 3. Derived State: computed()
A computed signal derives its value from other signals. It is read-only, lazy, and memoized.
### 3.1 Basic Usage and Memoization
```ts
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-cart-summary',
standalone: true,
template: `
([
{ id: 1, name: 'Angular Architecture Guide', category: 'books', price: 29 },
{ id: 2, name: 'Noise-Canceling Headphones', category: 'electronics', price: 199 },
{ id: 3, name: 'Hooded Sweatshirt', category: 'clothing', price: 49 },
{ id: 4, name: 'TypeScript Handbook', category: 'books', price: 34 }
]);
searchQuery = signal('');
selectedCategory = signal('all');
// 2. Computed Derived State: Memoized and recalculated on demand
filteredProducts = computed(() => {
const query = this.searchQuery().toLowerCase().trim();
const category = this.selectedCategory();
return this.allProducts().filter(product => {
const matchesQuery = product.name.toLowerCase().includes(query);
const matchesCategory = category === 'all' || product.category === category;
return matchesQuery && matchesCategory;
});
});
// 3. Side Effect: Synchronize search query to browser URL query params
constructor() {
effect(() => {
const query = this.searchQuery();
const url = new URL(window.location.href);
if (query) {
url.searchParams.set('q', query);
} else {
url.searchParams.delete('q');
}
window.history.replaceState(null, '', url.toString());
});
}
}
```
Count: {{ count() }}
User: {{ user().name }} (Active: {{ user().isActive }})
` }) export class CounterComponent { // Primitive signal (WritableSignalTotal Items: {{ itemCount() }}
Subtotal: {{ subtotal() | currency }}
Tax (18%): {{ tax() | currency }}
Grand Total: {{ grandTotal() | currency }}
` }) export class CartSummaryComponent { items = signal([ { name: 'Mechanical Keyboard', price: 90, qty: 1 }, { name: 'Gaming Mouse', price: 40, qty: 2 } ]); taxRate = signal(0.18); itemCount = computed(() => this.items().reduce((acc, item) => acc + item.qty, 0) ); subtotal = computed(() => this.items().reduce((acc, item) => acc + (item.price * item.qty), 0) ); tax = computed(() => this.subtotal() * this.taxRate()); // Compose computed signals from other computed signals grandTotal = computed(() => this.subtotal() + this.tax()); } ``` ### 3.2 computed() vs. Standard Class Getters ### Feature ### Standard Getter (get total()) Computed Signal (computed(() => ...)) ### Execution Rate ### Runs on every change detection pass Runs only when tracked dependencies change and the value is read ### Memoization ### None (recalculates every loop/formula) ### Built-in (caches previous value until dependencies change) ### Dependency Tracking ### Untracked by the framework Automatically builds a dynamic reactive graph ### 3.3 Dynamic Dependency Branching Computed signals track dependencies dynamically during execution. If a branch is skipped, any signal read inside it is excluded from the dependency graph: ```ts export class DynamicFilterComponent { showDiscounts = signal(false); basePrice = signal(100); discountPercentage = signal(20); finalPrice = computed(() => { if (!this.showDiscounts()) { // Tracks ONLY this.basePrice() return this.basePrice(); } // Tracks this.basePrice() AND this.discountPercentage() return this.basePrice() * (1 - this.discountPercentage() / 100); }); } ``` When showDiscounts is false, changing discountPercentage will not trigger recalculation of finalPrice. ## 4. Side Effects: effect() An effect() runs side-effecting operations whenever one or more tracked signals change. Unlike computed(), an effect returns no value—it bridges Angular state to the outside world (DOM, storage, logging, external SDKs). ### 4.1 Common Use Cases ### Syncing state to localStorage or sessionStorage ### Sending analytics or telemetry logs ### Imperative drawing with canvas, D3, or Chart.js ### Running manual DOM animations ```ts import { Component, signal, effect } from '@angular/core'; @Component({ selector: 'app-theme-switcher', standalone: true, template: ` ` }) export class ThemeSwitcherComponent { theme = signal<'light' | 'dark'>( (localStorage.getItem('user_theme') as 'light' | 'dark') ?? 'light' ); constructor() { // Re-runs whenever this.theme() changes effect(() => { const activeTheme = this.theme(); localStorage.setItem('user_theme', activeTheme); document.documentElement.setAttribute('data-theme', activeTheme); console.log(`Theme set to: ${activeTheme}`); }); } toggleTheme(): void { this.theme.update(t => t === 'light' ? 'dark' : 'light'); } } ``` ### 4.2 Injection Context and Destruction Effects require an injection context (the constructor, a field initializer, or an EnvironmentInjector.runInContext() callback). Angular attaches the effect's lifecycle to the host component or service; when the component unmounts, the effect is torn down automatically. To register an effect outside an injection context (e.g., inside ngOnInit), pass an explicit Injector: ```ts import { Component, effect, inject, Injector, OnInit } from '@angular/core'; @Component({ ... }) export class ManualEffectComponent implements OnInit { private injector = inject(Injector); data = signal('initial'); ngOnInit(): void { effect(() => { console.log('Data:', this.data()); }, { injector: this.injector }); } } ``` ### 4.3 Cleanup with onCleanup When an effect runs async operations (timers, WebSockets, DOM subscriptions), use the onCleanup callback to cancel pending tasks before the next run or upon component destruction: ```ts import { Component, signal, effect } from '@angular/core'; @Component({ ... }) export class SearchTelemetryComponent { query = signal(''); constructor() { effect((onCleanup) => { const currentQuery = this.query(); if (!currentQuery) return; const timer = setTimeout(() => { console.log('Sending metrics for:', currentQuery); }, 500); // Cancels previous timer if query updates before timeout finishes onCleanup(() => { clearTimeout(timer); }); }); } } ``` ### 4.4 The Golden Rule: Don't Mutate Signals Inside effect() By default, Angular throws a runtime error (NG0600) if you mutate a signal inside an effect(): ```ts // ❌ ANTI-PATTERN: Throws NG0600 effect(() => { if (this.count() > 10) { this.hasExceededMax.set(true); } }); ``` Mutating state inside effects can trigger recursive loops and reintroduces uncontrolled change cascades. The Fix: If state B depends on state A, express it as derived state using computed(): ```ts // ✅ Clean derived state hasExceededMax = computed(() => this.count() > 10); ``` ## 5. Untracking Dependencies with untracked() When you need to read a signal inside an effect or computed block without subscribing to its changes, wrap the read with untracked(): ```ts import { Component, signal, effect, untracked } from '@angular/core'; @Component({ ... }) export class NotificationComponent { message = signal('Welcome!'); currentUser = signal('John'); constructor() { effect(() => { // Tracked: Effect re-runs when message changes const msg = this.message(); // Untracked: Reading this value does not trigger a re-run when it changes const user = untracked(() => this.currentUser()); console.log(`Notification for ${user}: ${msg}`); }); } } ``` ## 6. Real-World Architecture: E-Commerce Catalog Filter Here is how signal(), computed(), and effect() work together in a complete search and filtering flow: ```ts // src/app/catalog/product-catalog.component.ts import { Component, signal, computed, effect } from '@angular/core'; import { CommonModule } from '@angular/common'; export interface Product { id: number; name: string; category: 'electronics' | 'books' | 'clothing'; price: number; } @Component({ selector: 'app-product-catalog', standalone: true, imports: [CommonModule], template: `
Showing {{ filteredProducts().length }} of {{ allProducts().length }} products
@for (prod of filteredProducts(); track prod.id) {
} @empty {
`
})
export class ProductCatalogComponent {
// 1. Base Writable State
allProducts = signal{{ prod.name }}
{{ prod.category }} {{ prod.price | currency }}No products match your search criteria.
}