Dependency Tracking
You'll learn how signals automatically know which computations or effects rely on them, eliminating manual subscription management.
The Invisible Subscription System
When you read a signal inside a computed or effect, something magical happens behind the scenes: the signal registers that computation as a dependent. Later, when the signal's value changes, it knows exactly which computations need to re-run. No manual .subscribe() calls, no explicit wiring—it just works.
Think of it like a librarian automatically recording everyone who reads a particular book. When that book gets a new edition, the librarian knows precisely who to notify without anyone having to sign a sheet.
How It Works
Dependency tracking relies on a global context stack. When an effect or computed starts executing, the signal system pushes it onto this stack. Any signal read during execution sees the current context and adds it to its dependency list. When execution finishes, the context is popped off.
let currentContext = null;
function createSignal(initialValue) {
let value = initialValue;
const dependencies = new Set();
return {
read() {
if (currentContext) {
dependencies.add(currentContext);
}
return value;
},
write(newValue) {
value = newValue;
dependencies.forEach(dep => dep.rerun());
}
};
}
This automatic tracking means signals scale effortlessly—you can have hundreds of computed values and effects, and each only updates when its actual dependencies change, not when unrelated signals update.
Key Takeaway: Dependency tracking automatically builds a precise graph of which computations depend on which signals by recording reads during execution, enabling surgical updates without manual subscription management.