Sub topic 4
Dependencies Are Discovered at Run Time
This chapter assumes you can read TypeScript and have used signal(), .set(), .update() and computed() in an Angular component. It builds on the previous chapters: a computed signal is lazy and caches its value. Here you will see how a computed signal decides what it depends on. That decision happens while the function runs, not when you write it.
Static and dynamic dependency lists
Some systems make you list dependencies up front. React's useMemo(fn, [a, b]) is one example. If the list is wrong, the cache is stale or recomputes too often.
Angular signals work differently. You never declare dependencies. While a computed function runs, Angular records every signal that function reads. That recorded set is the dependency list, and it is rebuilt on every evaluation.
Two things follow:
- A dependency exists only if the function actually reads the signal during its latest run.
- When a branch of the function stops executing, the signals read only in that branch stop being dependencies.
A computed that changes its mind
The next example uses the label computed from the topic plan. It adds a counter so you can see exactly when the function runs.
import { signal, computed } from '@angular/core';
let runs = 0;
const showDetails = signal(false);
const name = signal('Ada');
const details = signal('Mathematician');
const label = computed(() => {
runs++;
return showDetails() ? `${name()} - ${details()}` : name();
});
console.log(label(), runs); // 'Ada' 1
details.set('Programmer');
console.log(label(), runs); // 'Ada' 1
showDetails.set(true);
console.log(label(), runs); // 'Ada - Programmer' 2
details.set('Analyst');
console.log(label(), runs); // 'Ada - Analyst' 3
showDetails.set(false);
console.log(label(), runs); // 'Ada' 4
details.set('Poet');
console.log(label(), runs); // 'Ada' 4Follow the counter through the run:
- The first read evaluates the function with
showDetails()false. It readsshowDetailsandname, and never reachesdetails. The dependencies areshowDetailsandname. details.set('Programmer')changes a signal thatlabeldoes not depend on. The computed is not even marked dirty, so the second read returns the cached value andrunsstays at 1.showDetails.set(true)changes a dependency. The next read re-evaluates, and this time the function reachesdetails(). The dependencies are nowshowDetails,nameanddetails.details.set('Analyst')now matters, so the next read re-evaluates.showDetails.set(false)re-evaluates again. The function takes the short branch, sodetailsdrops out of the dependency set. The finaldetails.set('Poet')is ignored.
How it works internally
Each signal keeps a version number that goes up when its value changes. Each computed keeps a list of the signals it read last time, along with the version it saw for each one.
When a writable signal changes, it notifies its consumers. A computed consumer is marked as possibly stale. Nothing is recomputed at this point, because computed signals are lazy.
When the computed is read again, Angular checks whether any signal in its stored list has a newer version. If none does, it returns the cached value. If one does, it:
- Clears the old dependency list.
- Runs your function with tracking switched on.
- Records each signal read during that run as a new dependency.
- Compares the result with the old value using the computed's equality function. By default this is
Object.is.
Step 1 is why dynamic tracking works. The list is thrown away and rebuilt, so it always matches the code path that just ran. There is no separate cleanup step for signals that dropped out.
The same rule explains the unconditional case. A computed whose function reads no signals has an empty list, so nothing can ever invalidate it. It evaluates once and keeps that value.
Common ways to get conditional dependencies
Branches are the obvious source, but several other constructs have the same effect.
Ternaries and if statements
The label example is this case. Only the branch that runs contributes dependencies.
Short-circuit operators
&&, || and ?? skip their right-hand side in some cases. The skipped signal is not a dependency.
import { signal, computed } from '@angular/core';
const isLoggedIn = signal(false);
const unreadCount = signal(5);
const badge = computed(() => isLoggedIn() && unreadCount() > 0);
console.log(badge()); // false
unreadCount.set(9); // badge does not depend on unreadCount yet
isLoggedIn.set(true);
console.log(badge()); // trueWhile isLoggedIn() is false, unreadCount() is never called. Once the user logs in, the right-hand side runs and unreadCount becomes a dependency.
Early returns
import { signal, computed } from '@angular/core';
const query = signal('');
const items = signal(['apple', 'banana', 'cherry']);
const results = computed(() => {
const q = query();
if (q === '') {
return [];
}
return items().filter((item) => item.includes(q));
});With an empty query, items is not a dependency. Changing items does nothing until the user types something.
Loops over changing data
If a loop reads one signal per element, the dependency set depends on how many iterations ran. A computed that sums a list of signals stays correct when the list changes, as long as the list itself is a signal that the function reads.
What counts as a read
Tracking is tied to the call stack. Angular marks a computed as the active consumer while its function runs. Any signal read in that window is recorded. A read after the function has returned is not recorded.
| Where the read happens | Tracked? |
|---|---|
| Directly in the computed function body | Yes |
| In a helper function called synchronously from the body | Yes |
| Inside synchronous callbacks such as `map`, `filter`, `forEach` | Yes |
| Inside `untracked(() => ...)` | No, by design |
| After an `await` in an `async` function | No |
| In a `setTimeout` or `.then` callback | No |
| In a function the computed returns, called later by someone else | Not by this computed |
The first three rows are why ordinary code works without thought. Splitting logic into helper functions does not hide reads from the computed.
The async pitfall
An async function runs synchronously up to its first await. Everything after that runs later, when no computed is the active consumer.
import { signal, computed } from '@angular/core';
const userId = signal(1);
// Broken: nothing is read before the await, so there are no dependencies.
const broken = computed(async () => {
await Promise.resolve();
return `user-${userId()}`;
});
// Works: the signal is read synchronously, before any async work.
const working = computed(() => {
const id = userId();
return Promise.resolve(`user-${id}`);
});
userId.set(2);
broken().then(console.log); // 'user-1' (cached forever, never recomputed)
working().then(console.log); // 'user-2'The broken computed evaluates once, finds no dependencies and keeps its first promise indefinitely. In working, the read of userId() happens during the synchronous part, so the computed is tracked. Read every signal you need at the top of the function, before any await.
This is also a sign that computed() is for synchronous derivation. If the value comes from an asynchronous source, you need a different tool. Later chapters cover toSignal() and toObservable() for that.
Returning a function
import { signal, computed } from '@angular/core';
const price = signal(10);
const quantity = signal(2);
const makeTotal = computed(() => () => price() * quantity());makeTotal has no dependencies, because price() and quantity() are read inside the inner function, which runs only when someone calls it. Calling makeTotal()() still returns a correct number on every call. The cost is that the computed provides no caching, and whoever calls the inner function is the one that tracks the reads. This is almost never what you want. Prefer computed(() => price() * quantity()).
Practical consequences
Conditional reads can hide bugs
If a signal is only read in a branch you rarely take, you can change it for a long time with no visible effect. That is correct behavior, but it can look like a bug when you debug with the wrong branch active. When a computed "does not update", first check which branch ran last.
Put the reads you always need first
Reading a signal before a guard makes the dependency unconditional. This is a design choice, not a rule. Read a signal unconditionally when you want every change to it to trigger a re-evaluation, even if the output may not change. Read it conditionally when re-evaluating would be wasted work.
Dependencies are not contagious across the guard
A computed that reads another computed depends on it, not on its sources. If the inner computed's own dependencies change, the inner one re-evaluates first. The outer one re-evaluates only if the inner value actually changed.
Errors keep their dependencies
If the function throws, Angular caches the error and rethrows it on later reads. The signals read before the throw remain dependencies, so a later change to them clears the error on the next read. A thrown error does not leave the computed permanently broken.
Effects follow the same rule
An effect() also records its reads during each run and rebuilds the set every time. Everything in this chapter applies to effects. The effects chapters come later, along with untracked(), which lets you opt a read out of tracking on purpose.
Debugging a computed that does not update
Work through these checks in order:
- Add a counter or a
console.logat the top of the function. If it never runs after your change, the computed is not subscribed to that signal. - Check whether the signal is read on the path that last ran. A guard or short-circuit may be skipping it.
- Look for reads after an
awaitor inside asetTimeout. Move them above the first asynchronous boundary. - Check that you are reading the signal by calling it. Writing
quantityinstead ofquantity()reads the signal function object, not its value, and registers no dependency. TypeScript usually catches this in arithmetic, but not inif (quantity), which is always truthy. - Check mutation. If the signal holds an object and you mutated it in place, the reference did not change.
Object.issees the same value, so nothing is notified. Replace the object instead.
Exercise
A computed is defined as computed(() => enabled() ? data() : 'off'). enabled is false and the computed has just been read. You call data.set(...) three times, then enabled.set(true). How many times does the computed function run after the first read, and what does it depend on afterwards?
Show answer
It runs once more, on the next read after enabled.set(true). While enabled() was false, data was not a dependency, so the three data.set(...) calls did not mark the computed as stale. After the re-evaluation, the dependencies are enabled and data, because the function now reaches data().
Exercise
What is wrong with const result = computed(async () => { await delay(100); return factor() * 2; });, and how do you change it so that updates to factor produce a new result?
Show answer
factor() is read after an await, so no computed is the active consumer when it runs. The computed has no dependencies and keeps its first promise forever. Read the signal before the first await, for example const f = factor(); at the top, and then use f after the delay. Also remember that each re-evaluation creates a new promise.
Exercise
A computed uses isAdmin() && auditLog().length > 0. For a non-admin user, does changing auditLog cause the computed to re-evaluate? Explain why this does or does not matter.
Show answer
No. When isAdmin() is false, the right-hand side is skipped, so auditLog is not a dependency. This is the desired behavior, because the result is false no matter what the log contains. It would only matter if you expected the computed to react to the log before the user became an admin. Once isAdmin becomes true, the next evaluation reads auditLog and tracks it.