Sub topic 10
Fine-Tuning Reactivity: Equality and untracked()
Signals decide two things automatically. They decide when a value counts as "changed", and they decide which reads create dependencies. The defaults are right most of the time. Sometimes they are not: an effect re-runs too often, a computed signal sends notifications for results that look identical, or an effect starts depending on a signal it only meant to look at. This chapter covers the two tools Angular gives you for these cases: custom equality functions and untracked().
This chapter assumes you already know how to create writable signals with signal(), set(), and update(), how computed() derives and memoizes values, and how effect() runs inside an injection context.
How Signals Decide Something Changed
Every signal has an equality function. When you call set() or update(), Angular compares the new value with the current one. If the function says they are equal, nothing happens. The signal keeps its current value and no consumer gets notified.
The default equality function is Object.is. For primitives this compares values. For objects and arrays it compares references.
| Old value | New value | `Object.is` result | Consumers notified? |
|---|---|---|---|
| `3` | `3` | `true` | No |
| `'a'` | `'b'` | `false` | Yes |
| `NaN` | `NaN` | `true` | No |
| `{ id: 1 }` | a new `{ id: 1 }` | `false` | Yes |
| `arr` | the same `arr` after `push()` | `true` | No |
The last two rows cause most equality bugs. A new object with identical contents counts as a change. A mutated object with the same reference does not.
The mutation pitfall
Since the default check compares references, mutating an array or object in place and returning the same reference is invisible to signals:
import { computed, signal } from '@angular/core';
const tags = signal<string[]>(['angular']);
const count = computed(() => tags().length);
console.log(count()); // 1
// Wrong: same array reference, so Object.is says "equal"
tags.update(list => {
list.push('signals');
return list;
});
console.log(count()); // still 1: count was never marked dirty
// Right: return a new array
tags.update(list => [...list, 'rxjs']);
console.log(count()); // 3The final count is 3 because the mutated array really does hold 'signals'. The computed signal only notices once a new reference arrives. The fix is to treat signal values as immutable: return new arrays and objects from update().
Custom Equality Functions
Both signal() and computed() accept an options object with an equal property. It has the signature (a: T, b: T) => boolean.
Equality on a writable signal
Here is a component that treats two users with the same id as the same user:
import { Component, effect, signal, untracked } from '@angular/core';
interface User { id: number; name: string; }
@Component({ selector: 'app-user-log', template: '' })
export class UserLogComponent {
user = signal<User>(
{ id: 1, name: 'Ada' },
{ equal: (a, b) => a.id === b.id }
);
visits = signal(0);
constructor() {
effect(() => {
const current = this.user();
const count = untracked(() => this.visits());
console.log(`User ${current.name}, visits so far: ${count}`);
});
}
}If you call this.user.set({ id: 1, name: 'Ada' }) with a fresh object, the effect does not run again, because the ids match. That is the point of the custom equality: refetched data with the same identity does not cause downstream work.
This is the most common mistake with custom equality. "Equal" in Angular means "replaceable without anyone noticing", so the function should return true only when consumers would not care about the difference.
Equality on a computed signal
Equality on computed() works at the output side. When a computed signal recomputes and the new result equals the previous one, Angular keeps the previous value and does not tell downstream consumers that anything changed. Their own recomputation and any effects stay skipped.
This matters when a computed signal builds a new array or object every time it runs:
import { computed, signal } from '@angular/core';
interface Todo { id: number; title: string; done: boolean; }
const todos = signal<Todo[]>([
{ id: 1, title: 'Write docs', done: false },
{ id: 2, title: 'Ship', done: true },
]);
const sameIds = (a: number[], b: number[]) =>
a.length === b.length && a.every((v, i) => v === b[i]);
const doneIds = computed(
() => todos().filter(t => t.done).map(t => t.id),
{ equal: sameIds }
);
const summary = computed(() => {
console.log('summary recomputed');
return `Done: ${doneIds().join(', ')}`;
});
console.log(summary()); // logs "summary recomputed", then "Done: 2"
// Rename a todo: todos changes, doneIds recomputes to [2] again
todos.update(list =>
list.map(t => (t.id === 1 ? { ...t, title: 'Write better docs' } : t))
);
console.log(summary()); // "Done: 2" with no "summary recomputed" logWithout sameIds, doneIds would return a new [2] array, Object.is would report a change, and summary would recompute for nothing.
Writing good equality functions
- Keep them cheap. They run on every
set(),update(), and recomputation. A deep comparison of a large tree can cost more than the work it saves. - Make them pure and symmetric. They should depend only on
aandb, andequal(a, b)should matchequal(b, a). - Don't read signals inside them. Equality functions are not reactive contexts, and reading signals there makes the behavior hard to reason about.
- Prefer a shallow comparison for arrays of primitives and id comparison for entities. Use deep equality only for small values.
Reading Without Tracking: untracked()
Any signal you read inside a computed() or effect() becomes a dependency. Usually that is what you want. Sometimes you need the current value of a signal without reacting to its changes. untracked(fn) runs fn, returns its result, and records no dependencies for any signal read inside it.
In UserLogComponent, the effect depends on user only. Incrementing visits does not run the effect again. When user changes, the effect reads the latest visits value at that moment.
| Signal | Read with | Effect re-runs when it changes? |
|---|---|---|
| `user` | `this.user()` | Yes |
| `visits` | `untracked(() => this.visits())` | No |
Guarding against hidden dependencies
The less obvious use of untracked() is protecting an effect from signals read by code it calls. A service method, a logger, or a third-party callback may read signals internally. If you call it directly inside an effect, the effect quietly takes on those dependencies.
import { Component, Injectable, effect, inject, signal, untracked } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class AnalyticsService {
readonly sessionId = signal('s-001');
readonly debug = signal(false);
track(event: string) {
// Reads two signals internally
if (this.debug()) console.log(`[${this.sessionId()}] ${event}`);
}
}
@Component({ selector: 'app-page', template: '' })
export class PageComponent {
private analytics = inject(AnalyticsService);
page = signal('home');
constructor() {
effect(() => {
const current = this.page(); // the only intended dependency
untracked(() => this.analytics.track(`view:${current}`));
});
}
}Without untracked(), toggling debug or changing sessionId would log a new page view even though the user never navigated. Wrapping the call keeps the effect's dependency list to exactly what you read on purpose.
A useful habit: inside an effect, read every signal you depend on at the top, then do the side effect inside untracked(). The dependencies are then easy to see in one place.
untracked() in computed signals
untracked() works inside computed() too, but use it carefully. A computed value that depends on an untracked signal can go stale, because changes to that signal never invalidate the cache:
import { computed, signal, untracked } from '@angular/core';
const price = signal(100);
const rate = signal(1.2);
const converted = computed(() => price() * untracked(() => rate()));
console.log(converted()); // 120
rate.set(1.5);
console.log(converted()); // still 120: rate is not a dependency
price.set(200);
console.log(converted()); // 300: recomputed because price changed, using the latest rateSometimes this is intended, for example when you want a snapshot of a configuration value at the moment a primary input changes. If you don't intend it, it's a bug that is hard to spot. If the derived value has to be correct for every input, track every input.
Choosing the Right Tool
The two tools solve different problems. Equality controls whether a change in one signal counts as a change. untracked() controls whether a particular read creates a dependency at all.
| Symptom | Likely cause | Tool |
|---|---|---|
| Effect re-runs after refetching identical data | New object references each time | `equal` on the source signal |
| Downstream computed recomputes for identical arrays | Computed returns a new array each run | `equal` on the computed |
| Effect fires when an unrelated value changes | Hidden read inside a called function | `untracked()` around the call |
| Effect needs a value only as context | Direct read creates a dependency | `untracked()` around the read |
| Update does nothing | Mutation returned the same reference | Return a new object, no tool needed |
| Update silently dropped | Equality function ignores a changed field | Fix the equality function |
Exercise
A signal is created as signal({ id: 7, status: 'pending' }, { equal: (a, b) => a.id === b.id }). Later the code calls set({ id: 7, status: 'done' }). What does the signal return afterward, and do any effects that read it re-run?
Show answer
It still returns { id: 7, status: 'pending' }. The equality function reports the values as equal because the ids match, so Angular discards the new value and notifies nobody. To store the status change, include status in the comparison or drop the custom equality.
Exercise
An effect reads this.filter() and then calls this.store.save(this.filter()). The save method reads a signal named lastSavedAt internally and writes to it. Users report that the effect runs repeatedly. Why, and how do you fix it?
Show answer
Calling save inside the effect makes lastSavedAt a dependency of the effect. Every save writes lastSavedAt, which schedules the effect again and creates a loop. Read filter at the top of the effect and wrap the call: const f = this.filter(); untracked(() => this.store.save(f)); Now the effect depends only on filter.
Exercise
A computed signal returns items().map(i => i.name) and feeds an expensive computed chain. Updating an unrelated field on one item recomputes the whole chain. What change prevents this without touching the consumers?
Show answer
Give the names computed a shallow array equality function, such as { equal: (a, b) => a.length === b.length && a.every((v, i) => v === b[i]) }. When the names don't change, the computed keeps its previous array and reports no change, so the downstream chain stays cached.