Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 74 ยท Signals and Reactivity

Signals: signal, computed and effect

Learn Angular signals from the ground up - writable signals, lazy memoized computed values, effects, untracked and equality - with a runnable mini implementation.

Every interactive page has the same problem: some data changes, and everything that depends on it must update, and nothing else should. For years Angular solved this by re-checking whole component trees after any event. Signals solve it more precisely. A signal is a value that knows who reads it, so when it changes, Angular can tell exactly which derived values and which parts of the page are affected.

Signals are the foundation of modern Angular: component state, inputs, queries and the new forms and resource APIs are all built on them. This lesson covers the three building blocks, signal, computed and effect, plus untracked and custom equality. It also shows a working miniature implementation, so the behavior stops being magic.

Real Angular vs stand-in. The typescript blocks that import from @angular/core are real Angular, read-only on this site. The runnable examples use a hand-written signal graph (about 90 lines of TypeScript) that follows the same rules as Angular's: lazy, memoized, glitch-free. It is a teaching model, not Angular's source. If classes or closures feel shaky, revisit TypeScript classes and JavaScript closures.

Writable signals

signal() creates a writable signal: a function you call to read the value, with methods to change it.

TypeScript
import { signal } from '@angular/core';

const count = signal(0);

console.log(count()); // 0 (reading is calling the function)
count.set(5); // replace the value
count.update((value) => value + 1); // compute the next value from the current one
console.log(count()); // 6

Reading a signal is a function call, count(), not property access. That call is how Angular finds out who depends on what: whoever is running while the call happens is recorded as a consumer. In a template you write {{ count() }} and Angular records the template as a consumer of count.

A signal holds one value. For an object or array, you replace it with a new one instead of changing it in place:

TypeScript
const todos = signal<readonly string[]>(['write lesson']);
todos.update((list) => [...list, 'run examples']); // new array: consumers are notified
// todos().push('oops'); // do not do this: the signal never learns about it

Use .asReadonly() to hand out a version that can be read but not set, which is handy for exposing state from a service.

computed: derived values

A computed signal derives its value from other signals. You never set it; you describe how it is calculated:

TypeScript
import { computed, signal } from '@angular/core';

const price = signal(20);
const quantity = signal(3);
const total = computed(() => price() * quantity());

Three properties make computed powerful:

  • Lazy. The function does not run until somebody reads total(). A computed that nobody reads costs nothing.
  • Memoized. The result is cached. Reading total() twice runs the function once, until price or quantity changes.
  • Dynamic dependencies. Angular records which signals were actually read on the last run. If a branch skips a signal, a change to that signal does not recompute the value.

Derived data should almost always be a computed rather than a second signal you keep in sync by hand, because a hand-synchronized copy can get out of date. You will see that pattern repeatedly in Signals in Components.

flowchart LR
  A["a (signal)"] --> B["b = a * 2<br/>(computed)"]
  A --> C["c = a + 10<br/>(computed)"]
  B --> D["d = b + c<br/>(computed)"]
  C --> D
  D --> E["effect:<br/>log d"]

A diamond-shaped graph: when a changes once, d and the effect each run once, with consistent values.

effect: reacting to changes

An effect runs a function and re-runs it whenever a signal it read changes. It is how signals reach the world outside the graph: logging, saving to storage, updating a third-party widget.

TypeScript
import { Component, effect, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `<button (click)="count.update(c => c + 1)">{{ count() }}</button>`,
})
export class CounterComponent {
  count = signal(0);

  constructor() {
    effect((onCleanup) => {
      const value = this.count();
      const id = setTimeout(() => console.log('settled at', value), 500);
      onCleanup(() => clearTimeout(id)); // runs before the next run and on destroy
    });
  }
}

Things to know about effects:

  • They need an injection context (a constructor or field initializer), and they are destroyed automatically with their component or service.
  • They never run inside set(). Angular schedules them and runs them as part of change detection, and each effect runs at least once. Several set calls in a row are batched, so the effect sees only the final value.
  • An effect re-runs only when a signal it read changes, and only if that signal's value really changed.
  • The callback can take an onCleanup function for work that must be undone before the next run.
  • Writing to signals inside an effect is allowed in current versions, but it is usually a sign that you wanted computed (or linkedSignal, covered later). Use effects for side effects, not for deriving state. The effect API is stable as of Angular 20.

untracked and equality

Sometimes an effect or computed needs to read a signal without depending on it. Wrap the read in untracked:

TypeScript
effect(() => {
  const user = currentUser(); // tracked: re-run when the user changes
  const theme = untracked(() => themeSignal()); // read, but not a dependency
  console.log(`${user} prefers ${theme}`);
});

By default a signal considers a new value "changed" when Object.is(old, new) is false. A signal (or computed) can take a custom equal function:

TypeScript
const user = signal({ id: 1, name: 'Ada' }, { equal: (a, b) => a.id === b.id });

Now setting another object with the same id is ignored, and nothing downstream re-runs. Both options are useful, but the defaults are right most of the time.

Build a tiny signal graph

The best way to understand signals is to see how little machinery they need. The implementation below is a miniature of the same design: pushing a "may be stale" notification when a signal is set, and pulling fresh values lazily when something reads them. Each producer has a version number, so a consumer can ask "did anything I read really change?" before it recomputes.

TypeScript Stand-in: a miniature signal, computed and effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the output against the rules you just learned. In section 1, lazy does not compute until it is read, and then only once for two reads. After a.set(2), each of d, b and c computes exactly once, and the effect prints a single consistent value; there is never a moment where it sees b updated but c old. That is what glitch-free means. Three set calls before one flush produce a single effect run with the last value. In section 2, parity is recomputed when n becomes 4, but its result is unchanged, so its consumer, the effect, does not run. Section 3 shows untracked, and section 4 shows why you must replace arrays and objects rather than change them in place: the signal's version never changed, so the cached count stayed at 0.

Angular's real implementation adds many details (equality checks, cycle detection, scheduling integrated with rendering, memory management with weak references), but the shape is the same.

A signal-driven UI

This second stand-in is for the browser. It is simpler than the one above: updates are eager and synchronous, with no versions or laziness, which is fine for a small demo but is not how Angular behaves. A cart total is a computed, and an effect writes it into the page.

Stand-in: signals driving a small page

Press the buttons and watch the counter at the bottom: only signals that something read cause the page effect to run again. Because this version is eager, you may see it run slightly more often than Angular's would.

How this fits into Angular

Signals plug into the framework at several points, each covered in the following lessons: component state (Signals in Components), signal-based input(), model() and queries, async data with resource, and fine-grained updates in Change Detection, OnPush and Zoneless. The rule of thumb for choosing a tool:

  • Plain state that changes: signal.
  • Anything that can be calculated from other state: computed.
  • Something that must happen because state changed, outside the graph: effect, used sparingly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you read the current value of const count = signal(0)?

    A signal is a function. Calling it returns the value and registers the caller as a consumer.
  2. 2. A computed signal's function is called when the computed is created. True or false?

    Computed signals are lazy and memoized, so unread computeds cost nothing and repeated reads reuse the cached result.
  3. 3. You call items().push('x') on items = signal<string[]>([]). What happens to consumers?

    Signals detect change by comparing values (Object.is by default). Replace the array with items.update(l => [...l, 'x']).
  4. 4. What does untracked(() => other()) do inside an effect?

    untracked hides reads from dependency tracking, so changes to other do not re-run the effect.
  5. 5. Which is the best tool for a value that can always be calculated from existing signals?

    Derived state belongs in computed: it is always consistent, lazy and cached. Effects are for side effects outside the graph.

Summary

  • signal(initial) holds a value. Read it by calling it; change it with set or update, and replace objects and arrays instead of mutating them.
  • computed(fn) derives a value. It is lazy, memoized and tracks dependencies dynamically.
  • effect(fn) runs side effects when the signals it read change. It is scheduled by Angular, batched, needs an injection context and is cleaned up automatically.
  • untracked reads without creating a dependency; the equal option customizes what counts as a change.
  • The graph is glitch-free: derived values and effects always see a consistent state.

Next: Signals in Components