What if the language had dependency-tracking reactivity?
For example, with some contrived syntax, in the following example, any time foo or bar change, both values are logged to console:
reactive foo = 0
reactive bar = 0
autorun {
console.log(foo, bar)
}
setInterval(() => foo++, 1000)
setInterval(() => bar++, 820)
The autorun
expression reruns any time any of the reactive variables (auto-detected dependencies of the autorun) change. By using the variables inside the autorun, the system automatically tracks those variables as dependencies of the autorun, and that's how it knows to automatically rerun the expression if any of the dependencies change.
For those not familiar with dependency-tracking reactivity, it is a key feature in these libs or frameworks (note that API naming varies across them):
and many more.
If we want to stop logging in the above example, we could perhaps write
reactive foo = 0
reactive bar = 0
const stop = autorun {
console.log(foo, bar)
}
setInterval(() => foo++, 1000)
setInterval(() => bar++, 820)
// Stop the autorun (stop logging) later:
setTimeout(stop, 10_000)
I also wrote about how dependency-tracking reactivity makes code shorter, cleaner, and more concise compared to other event patterns here:
Do you think we can have a language-level dependency-tracking reactivity feature built in?