Computeds
Derive values from signals and keep them in sync without writing the syncing yourself.
A computed is a value worked out from other signals. You describe how to derive it once, and Xote keeps it in sync, so you never update two signals by hand.
Important:
Computed.makereturns aSignal.t<'a>. You read it withSignal.getorSignal.peek, like any other signal. It has noset: only its function writes it.
Create a computed
Pass Computed.make a function. Every signal the function reads becomes an input.
1open Xote23let price = Signal.make(100)4let quantity = Signal.make(3)56let subtotal = Computed.make(() =>7 Signal.get(price) * Signal.get(quantity)8)
Computed.make also accepts ~equals. By default a computed doesn't compare: when it recalculates, everything that reads it runs again, even if the new value is the same. Pass ~equals (for example ~equals=(a, b) => a == b) and an equal result leaves its dependents alone.
Read a computed
Read a computed exactly like a signal: Signal.get to subscribe, Signal.peek for a one-off read. A computed can depend on another computed.
1let subtotal = Computed.make(() =>2 Signal.get(price) * Signal.get(quantity)3)45let total = Computed.make(() =>6 Signal.get(subtotal) + 507)89Console.log(Signal.get(total))
Recomputing only when read
When an input changes, a computed is marked dirty right away, but it only recomputes when someone reads it. Derived values nobody uses cost almost nothing.
1let count = Signal.make(0)23let doubled = Computed.make(() => {4 Console.log("recomputing")5 Signal.get(count) * 26})78Signal.set(count, 1)9// Nothing logged yet1011ignore(Signal.get(doubled))12// Logs "recomputing"
Conditional dependencies
A computed collects its inputs again every time it runs, so conditionals are fine: whichever branch runs decides which signals it depends on.
1let useMetric = Signal.make(true)2let celsius = Signal.make(20)3let fahrenheit = Signal.make(68)45let temperature = Computed.make(() =>6 if Signal.get(useMetric) {7 Signal.get(celsius)8 } else {9 Signal.get(fahrenheit)10 }11)
Example: order summary
A common pattern: keep the writable state small, then derive the display values, like subtotal, shipping and total, from it.
1open Xote23let unitPrice = Signal.make(24)4let quantity = Signal.make(2)5let expressShipping = Signal.make(false)67let subtotal = Computed.make(() =>8 Signal.get(unitPrice) * Signal.get(quantity)9)1011let shippingCost = Computed.make(() =>12 if Signal.get(expressShipping) {13 1514 } else {15 016 }17)1819let total = Computed.make(() =>20 Signal.get(subtotal) + Signal.get(shippingCost)21)2223@xote.component24let make = () => {25 <div>26 <p> {"Subtotal: quot;} {Signal.get(subtotal)} </p>27 <p> {"Shipping: quot;} {Signal.get(shippingCost)} </p>28 <p> {"Total: quot;} {Signal.get(total)} </p>29 </div>30}Order Summary
The writable state is unit price, quantity, and shipping mode. Everything else is derived.
Cleaning up
Most computeds need no cleanup. They dispose themselves when nothing subscribes to them anymore, and one created inside a component or effect goes away with it.
If you create a long-lived computed outside any component and want to tear it down yourself, call Computed.dispose.
1let doubled = Computed.make(() => Signal.get(count) * 2)23// Use it for a while...45Computed.dispose(doubled)
Derive, don't copy
If a value can be derived from other signals, use a computed instead of copying it into another signal.
1// Avoid this2let count = Signal.make(0)3let doubled = Signal.make(0)45let increment = () => {6 Signal.update(count, n => n + 1)7 Signal.set(doubled, Signal.get(count) * 2)8}910// Prefer this11let count = Signal.make(0)12let doubled = Computed.make(() => Signal.get(count) * 2)
Tips
- Keep computeds pure. If the code talks to the outside world, it belongs in an effect.
- Read computeds with
Signal.getorSignal.peek; they are signals at the type level. - Don't copy derived values into writable signals unless you really need editable local state.
- Pass
~equalswhen a computed often recalculates to the same value and the things that read it are costly to run again. - To show derived values in the UI, read them in a component's JSX; see Rendering.
Summary
A computed is a read-only Signal.t<'a> whose value is produced by a function of other signals. Computed.make(fn) runs fn once immediately to get the initial value and record its dependencies; afterwards it is lazy: a change to a dependency only marks it dirty, and fn re-runs on the next read (or when an effect that depends on it is about to run). Use a computed whenever a value can be derived; never keep a second signal in sync by hand.
Availability
| Item | Value |
|---|---|
| Module | Xote.Computed (re-export of rescript-signals 3.1.x Signals.Computed) |
| Import / entry | xote (with "-open Xote": Computed.*), also xote/computed |
| First stable version | Computed.make and Computed.dispose are in 7.1.0 stable (and earlier) |
| Changes in 7.2.0 | None |
Requires @xote.component (PPX) | No |
Rules
Computed.make(fn)callsfnsynchronously duringmake, under tracking. EverySignal.getin that call becomes a dependency. Iffnthrows,makethrows and no computed is created.- The result is a
Signal.t<'a>. Read it withSignal.get(tracked) orSignal.peek(untracked), anywhere a signal is accepted, including as a dependency of another computed. - When a dependency changes, the computed is marked dirty;
fnis not called yet. It is recomputed when read (getorpeek) while dirty. Several writes before a read cause one recompute. - Dependencies are re-collected on every run. A signal read only in a branch that did not execute this time is dropped as a dependency (dynamic dependencies).
- Without
~equals, every recompute counts as a change: dependents (effects, reactive leaves, downstream computeds) re-run even if the new value equals the old one. - With
~equals, a recompute whose result is equal (per~equals(previous, next)) to the previous value does not propagate: dependent effects and leaves do not re-run. Use~equals=(a, b) => a == b(structural) or(a, b) => a === b(reference) to suppress no-op updates. - If
fnthrows during a recompute, the read that triggered it throws the same exception; the computed stays dirty and recomputes on the next read after a dependency changes. Inside a component subtree wrapped inView.ErrorBoundary(7.2.0), a throw from a reactive leaf reading the computed goes to that boundary. - A computed with no subscribers detaches from its sources: it stops receiving notifications and does no work until read again; a read checks whether any source changed and recomputes only then. This is how computeds created inside a component are released when the component's leaves and effects are disposed.
Computed.dispose(c)detachescimmediately (unlinks its dependencies). The computed remains readable: the next read recomputes and re-collects dependencies. It is only needed for a long-lived computed that still has subscribers you want to cut off.- A computed has no setter.
Signal.settype-checks on it (it is aSignal.t) but MUST NOT be used: the written value is overwritten by the next recompute. fnMUST be pure: no writes to signals, no DOM access, no network. Side effects belong in effects.
API
| Name | Signature | Behaviour |
|---|---|---|
Computed.make | (unit => 'a, ~name: string=?, ~equals: ('a, 'a) => bool=?) => Signal.t<'a> | Runs fn now; recomputes lazily when a dependency changes. ~equals suppresses propagation of equal results. |
Computed.dispose | Signal.t<'a> => unit | Detaches the computed from its sources; next read recomputes. |
Signal.get / Signal.peek | Signal.t<'a> => 'a | Read a computed (tracked / untracked); recomputes first if dirty. |
MaybeSignal.computed | (unit => 'a) => MaybeSignal.t<'a> | MaybeSignal.reactive(Computed.make(fn)); for APIs that take MaybeSignal.t. |
Patterns
Derived value used in JSX. Use when a displayed value depends on one or more signals.
1type item = {name: string, price: float, quantity: int}2let cart: Signal.t<array<item>> = Signal.make([])3let total = Computed.make(() =>4 Signal.get(cart)->Array.reduce(0.0, (sum, item) => sum +. item.price *. Int.toFloat(item.quantity))5)67module Total = {8 @xote.component9 let make = () => <p> {"Total: "} {Signal.get(total)->Float.toFixed(~digits=2)} </p>10}
Suppress no-op updates with ~equals. Use when a computed often recomputes to the same value (booleans, counts, filtered lists compared by value).
1let items = Signal.make([1, 2, 3])2let hasItems = Computed.make(() => Array.length(Signal.get(items)) > 0, ~equals=(a, b) => a == b)
Chained computeds. Use to split a derivation into named steps; each step is cached separately.
1let query = Signal.make("")2let names = Signal.make(["Ada", "Grace", "Alan"])3let normalized = Computed.make(() => Signal.get(query)->String.trim->String.toLowerCase)4let matches = Computed.make(() => {5 let q = Signal.get(normalized)6 Signal.get(names)->Array.filter(name => String.toLowerCase(name)->String.includes(q))7}, ~equals=(a, b) => a == b)
Conditional dependencies. Use when part of the input matters only in some states; unused signals stop being dependencies.
1let showDetails = Signal.make(false)2let name = Signal.make("Ada")3let details = Signal.make("Mathematician")4let label = Computed.make(() =>5 Signal.get(showDetails) ? Signal.get(name) ++ ": " ++ Signal.get(details) : Signal.get(name)6)
Anti-patterns
- Syncing a second signal with an effect.
1let first = Signal.make("Ada")2let last = Signal.make("Lovelace")3let full = Signal.make("")4Effect.run(() => {5 Signal.set(full, Signal.get(first) ++ " " ++ Signal.get(last))6 None7})
Symptom: works, but there is a window where full is stale during a batch, an extra effect and an extra signal to keep consistent, and readers can still set full by mistake. Fix:
1let first = Signal.make("Ada")2let last = Signal.make("Lovelace")3let full = Computed.make(() => Signal.get(first) ++ " " ++ Signal.get(last))
Why: a computed is always consistent with its sources on read (rule 3) and cannot be written.
- Expecting equal results to be free without
~equals.
1let count = Signal.make(1)2let isOdd = Computed.make(() => mod(Signal.get(count), 2) == 1)3// Signal.set(count, 3): isOdd is still true, but every effect/leaf reading it runs again
Symptom: effects that depend on isOdd run on every change to count. Fix: add ~equals=(a, b) => a == b.
Why: rule 5. Without ~equals a recompute always propagates.
- Side effects inside the function.
1let count = Signal.make(0)2let logged = Computed.make(() => {3 Console.log(Signal.get(count)) // runs only when someone reads it, possibly never4 Signal.get(count)5})
Symptom: logs appear irregularly (only on reads after a change) or never, and duplicate when read from several places after a change. Fix: put the side effect in Effect.run.
Why: rule 3. A computed runs on demand, not on change.
- Creating a computed inside a reactive leaf or a frequently re-running effect.
1let count = Signal.make(0)2Effect.run(() => {3 let doubled = Computed.make(() => Signal.get(count) * 2) // a new computed each run4 Console.log(Signal.get(doubled))5 None6})
Symptom: extra allocation and recomputation on every run; the old computeds are only released when they lose their subscriber. Fix: create the computed once (module level or component body) and read it in the effect.
Edge cases
- The initial value is computed eagerly at
make(rule 1), even if nothing ever reads it.MaybeSignal.computedhas the same behaviour. Signal.peekon a dirty computed recomputes it.- Reading a computed inside
Signal.batchreturns the up-to-date value; the batch only delays effects. - Inside a flush, an effect that depends on a computed declared with
~equalsis not queued until the computed has been recomputed; if the result is equal, the effect does not run at all. - Recursion: a computed that reads itself (directly or through another computed) is not supported.
- A computed created at module level lives for the process. It costs nothing while it has no subscribers (rule 8).
~nameis stored as a debugging label only; Xote does not read it.
SSR and hydration
- During server rendering, computeds read by the rendered tree are evaluated with the current signal values. There is no later update on the server.
- A module-level computed in a server process is shared across requests, like any module-level value; derive request state inside the tree.
- Nothing about a computed is serialised for hydration; on the client it is re-created by the same code and recomputed from the (hydrated) signals.
Verify
Computed.makereturnsSignal.t<'a>; a type error mentioningSignal.twhere a plain value is expected means a missingSignal.get.- Behaviour check:
1let count = Signal.make(1)2let runs = ref(0)3let isOdd = Computed.make(() => mod(Signal.get(count), 2) == 1, ~equals=(a, b) => a == b)4Effect.run(() => {5 let _ = Signal.get(isOdd)6 runs := runs.contents + 17 None8})9Signal.set(count, 3) // isOdd recomputes to true: equal, effect does not run10// runs.contents == 1; without ~equals it would be 2
- Laziness check: put a counter in
fn, write the source twice without reading, then read once; the counter increases by exactly one.
Related
/docs/learn/signals— writes, equality and synchronous flushing that drive recomputation./docs/learn/effects— where side effects that depend on a computed go./docs/advanced/batching— computeds stay readable and fresh inside a batch./docs/api/computed— full reference fromsrc/Computed.resi./docs/glossary— terms used on this page.
API reference
This page lists the supported API for the Computed module.
Computed
Computed creates derived signals. A computed value has type Signal.t<'a>, so you read it with Signal.get or Signal.peek.
Computed.make
1let make: (2 unit => 'a,3 ~name: option<string>=?,4 ~equals: option<('a, 'a) => bool>=?,5) => Signal.t<'a>
Create a lazily recomputed derived signal. ~equals controls whether recomputed values propagate to downstream observers.
Computed.dispose
1let dispose: Signal.t<'a> => unit
Manually disconnect a computed from its dependencies. Most UI-owned computeds are cleaned up through DOM ownership and do not need manual disposal.
Example
1open Xote23let count = Signal.make(0)4let doubled = Computed.make(() => Signal.get(count) * 2)56Console.log(Signal.get(doubled))