Sub topic 9
Custom equality functions
This chapter assumes you can read TypeScript and have used signal(), computed() and effect() in Angular. You should know that a computed value is lazy and cached, and that reading a signal inside a computed or effect registers a dependency. Here you will learn how Angular decides that a signal's value has changed, and how to change that rule when the default does not fit your data.
How Angular decides a value changed
Every writable signal and every computed signal holds an equality function. After a new value is produced, Angular calls it with the old and new values. The default is Object.is, which compares by reference for objects and arrays, and by value for primitives.
- If the function returns
false, the value counts as changed. Angular stores the new value and marks consumers (computed signals, effects, templates) as needing a refresh. - If it returns
true, Angular keeps the old value and does not notify anyone.
The second case is the useful one. A computed signal that recalculates but gets an "equal" result acts as a firewall. Everything downstream of it stays clean and does not run again.
The problem: new references every time
Methods such as filter(), map() and slice(), and object spreads like { ...x }, always create a new array or object. Even when the contents are identical, Object.is sees two different references.
Consider this computed signal:
import { signal, computed } from '@angular/core';
interface Item { id: number; done: boolean; }
const items = signal<Item[]>([
{ id: 1, done: true },
{ id: 2, done: false },
]);
const doneItems = computed(() => items().filter((i) => i.done));Whenever items changes, doneItems recalculates and returns a brand-new array. With the default equality, every consumer of doneItems is told it changed, even if the same items are still in it. A list in a template re-checks its bindings, and an effect that depends on doneItems runs again for no reason.
The `equal` option of computed()
computed() takes a second argument, an options object. Its equal property is a function (a, b) => boolean, where a is the previous value and b is the new one.
import { signal, computed } from '@angular/core';
interface Item { id: number; done: boolean; }
const items = signal<Item[]>([
{ id: 1, done: true },
{ id: 2, done: false },
]);
const doneItems = computed(() => items().filter((i) => i.done), {
equal: (a, b) => a.length === b.length && a.every((v, i) => v === b[i]),
});This function says two arrays are equal when they have the same length and each position holds the same object reference. It is a shallow comparison. It does not look inside the items.
You can watch the firewall work by counting how often a downstream computed runs:
import { signal, computed } from '@angular/core';
interface Item { id: number; done: boolean; }
const sameItems = (a: Item[], b: Item[]) =>
a.length === b.length && a.every((v, i) => v === b[i]);
const items = signal<Item[]>([
{ id: 1, done: true },
{ id: 2, done: false },
]);
const doneItems = computed(() => items().filter((i) => i.done), {
equal: sameItems,
});
let summaryRuns = 0;
const summary = computed(() => {
summaryRuns++;
return `${doneItems().length} done`;
});
console.log(summary(), summaryRuns); // '1 done' 1
// Replace item 2 with a new object that is still not done.
items.update((list) =>
list.map((i) => (i.id === 2 ? { ...i, done: false } : i))
);
console.log(summary(), summaryRuns); // '1 done' 1When items changes, doneItems is marked dirty. Reading summary() makes Angular check whether doneItems really changed. doneItems recalculates and produces [item1], the same contents as before, so sameItems returns true. Angular keeps the old array, and summary does not need to run again. Remove the equal option and summaryRuns becomes 2.
The equal option of signal()
Writable signals accept the same option as their second argument:
import { signal } from '@angular/core';
const point = signal(
{ x: 0, y: 0 },
{ equal: (a, b) => a.x === b.x && a.y === b.y }
);
point.set({ x: 0, y: 0 }); // equal, so nothing is notified
point.set({ x: 1, y: 0 }); // different, so consumers are notifiedThis is useful when callers tend to set a fresh object that holds the same data, for example when mapping a server response into a signal on every poll.
Equality also applies to update(). The callback's return value goes through the same comparison as a value passed to set().
Default equality and in-place mutation
The default Object.is is also why mutating a value in place does not work:
import { signal } from '@angular/core';
const tags = signal<string[]>(['a']);
tags().push('b'); // mutates the array, signal is not notified
tags.set(tags()); // same reference, so equal, so no notification
tags.update((t) => [...t, 'c']); // new reference, so notificationPrefer immutable updates. Do not "fix" this by giving the signal an equal that always returns false. That forces a notification on every write, and it hides bugs where the array was changed without a set() call.
Writing a good equal function
Keep these rules in mind.
- Make it pure and fast. Angular may call it every time the signal is written or recalculated. It must not read other signals, log, or have side effects.
- Make it symmetric and consistent.
equal(a, b)andequal(b, a)should agree. Treat it as a real equivalence relation. - Compare only what consumers care about. If the template only shows
idandtitle, comparing those two fields is enough. - Prefer shallow over deep. A deep comparison of a large structure can cost more than the downstream work you wanted to skip.
- Remember that the old value is kept. When
equalreturnstrue, consumers keep seeing the previous value, not the new one.
A reusable helper for arrays of primitives or stable references:
import { signal, computed } from '@angular/core';
export function shallowArrayEqual<T>(a: readonly T[], b: readonly T[]): boolean {
return a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
}
const numbers = signal([3, 1, 2]);
const sorted = computed(() => [...numbers()].sort((x, y) => x - y), {
equal: shallowArrayEqual,
});
console.log(sorted()); // [1, 2, 3]Gotcha: ignoring differences hides real updates
An overly loose equal makes the signal silently drop updates. Here the signal considers two users equal when they share an id:
import { signal } from '@angular/core';
interface User { id: number; name: string; }
const user = signal<User>(
{ id: 1, name: 'Ada' },
{ equal: (a, b) => a.id === b.id }
);
user.set({ id: 1, name: 'Grace' });
console.log(user().name); // 'Ada'The second set() was treated as "no change", so the stored value stays { id: 1, name: 'Ada' }. The new name is lost, not just hidden from consumers. Use an id-only comparison on a signal only if dropping the other fields is truly what you want. Otherwise compare every field a consumer reads.
A second trap is tolerance-based comparison, such as treating two numbers as equal when they differ by less than 0.01:
import { signal } from '@angular/core';
const reading = signal(0, { equal: (a, b) => Math.abs(a - b) < 0.01 });
reading.set(0.006); // ignored, value stays 0
reading.set(0.012); // compared with 0, not with 0.006, so this is a changeEach new value is compared with the last accepted value, not the last attempted one. Small steps do not accumulate, but they can add up to a visible gap before one finally passes the threshold. That is usually acceptable for a noisy sensor and wrong for money.
Equality applies to the whole graph
The equal option works the same way in all places a signal appears:
| Where | Example | Effect of `equal` returning `true` |
|---|---|---|
| `signal()` | `signal(v, { equal })` | The write is ignored and the old value stays |
| `computed()` | `computed(fn, { equal })` | The old result is kept and consumers stay clean |
| `linkedSignal()` | `linkedSignal({ source, computation, equal })` | The same rule as the other two, applied to the recomputed value |
An effect has no equal option because it produces no value. It runs again only when a signal it read has changed under that signal's own equality rule. This is why a good equal on a computed signal can quietly cut the number of times an effect runs.
Choosing whether to add a custom equal
Do not add equal to every computed signal. The default is correct for primitives, and a comparison function is extra code that can be wrong. Add one when all of these hold:
- The computed signal returns a new array or object on every run.
- Its value is often structurally the same as before.
- Downstream work (a heavy template, an effect that calls an API) is expensive enough to be worth skipping.
If the result is a string, number or boolean, the default already does the right thing.
Summary of the model
- Angular compares the old and new value of every signal with its
equalfunction,Object.isby default. - A
trueresult keeps the old value and stops notifications from spreading. filter(),map()and spreads create new references, so computed signals built on them benefit from a shallow comparison.- A too-loose
equalon a writable signal discards real updates.
Exercise
A computed signal visible = computed(() => todos().filter(t => !t.hidden)) feeds a list in the template. After you add equal: (a, b) => a.length === b.length, the list no longer updates when a todo is swapped for a different one, as long as the number of visible todos stays the same. Why does this happen, and how do you fix the comparison?
Show answer
The comparison only checks length, so two arrays with the same number of items are treated as equal even when they contain different todos. Angular then keeps the old array and does not notify the template. Compare the elements too, for example a.length === b.length && a.every((v, i) => v === b[i]), so a different object at any position makes the arrays unequal.
Exercise
Given const count = signal(0, { equal: (a, b) => Math.floor(a / 10) === Math.floor(b / 10) });, what do count() return after count.set(5), and after count.set(12)?
Show answer
After count.set(5) it returns 0. The floor of 5 / 10 is 0, the same as for 0, so the write is treated as equal and the old value 0 is kept. After count.set(12) it returns 12. The floor of 12 / 10 is 1, which differs from the floor of 0 / 10, so the new value is stored.