Computed Values
computed(|| { ... }) encapsulates a derivation: the body runs on the first read
and stays cached until any signal read inside it changes. Unlike effect,
it is lazy — it only recalculates when someone reads it.
Tracking is transitive: an effect that reads a computed becomes dependent
on all signals that computed depends on. This makes it safe to compose computeds
in a chain without losing reactivity.
doubled recalculates on every change to count; the effect sees both in sync.
03-computed-derived.zolo
// Feature: computed — a memoized signal derived from other signals
// Syntax: `computed(|| { ... })`. The body is re-run when any signal
// it reads changes. Reads are tracked transitively: an effect that
// reads a computed depends on whatever the computed depends on.
// When to use: derived values that should recompute lazily and be
// shared between effects (full name, total price, formatted string).
let count = signal(0)
let doubled = computed(|| { count.get() * 2 })
let e = effect(|| {
print("count = {count.get()}, doubled = {doubled.get()}")
})
// expected: count = 0, doubled = 0
count.set(5)
// expected: count = 5, doubled = 10
count.set(7)
// expected: count = 7, doubled = 14
// Computed values cache: reading `doubled` twice in one effect run
// re-uses the result — the body only runs when a dep changes.
Challenge
Add a third computed called label that returns "even" or "odd" and
include it in the effect's print.
See also