Skip to content

Computeds

Derive values from signals and keep them in sync without writing the syncing yourself.

docs/learn/computeds.md
moduleXote.Computedboundarysrc/Computed.resientryxote · xote/computedversion7.2.0
Raw MarkdownAPI reference

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.make returns a Signal.t<'a>. You read it with Signal.get or Signal.peek, like any other signal. It has no set: only its function writes it.

Create a computed

Pass Computed.make a function. Every signal the function reads becomes an input.

1open Xote
2
3let price = Signal.make(100)
4let quantity = Signal.make(3)
5
6let 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)
4
5let total = Computed.make(() =>
6 Signal.get(subtotal) + 50
7)
8
9Console.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)
2
3let doubled = Computed.make(() => {
4 Console.log("recomputing")
5 Signal.get(count) * 2
6})
7
8Signal.set(count, 1)
9// Nothing logged yet
10
11ignore(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)
4
5let 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.

OrderSummary.res
1open Xote
2
3let unitPrice = Signal.make(24)
4let quantity = Signal.make(2)
5let expressShipping = Signal.make(false)
6
7let subtotal = Computed.make(() =>
8 Signal.get(unitPrice) * Signal.get(quantity)
9)
10
11let shippingCost = Computed.make(() =>
12 if Signal.get(expressShipping) {
13 15
14 } else {
15 0
16 }
17)
18
19let total = Computed.make(() =>
20 Signal.get(subtotal) + Signal.get(shippingCost)
21)
22
23@xote.component
24let 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.

Quantity
2
Plan
Shipping
Subtotal$48
Shipping$0
Total$48

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)
2
3// Use it for a while...
4
5Computed.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 this
2let count = Signal.make(0)
3let doubled = Signal.make(0)
4
5let increment = () => {
6 Signal.update(count, n => n + 1)
7 Signal.set(doubled, Signal.get(count) * 2)
8}
9
10// Prefer this
11let 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.get or Signal.peek; they are signals at the type level.
  • Don't copy derived values into writable signals unless you really need editable local state.
  • Pass ~equals when 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

ItemValue
ModuleXote.Computed (re-export of rescript-signals 3.1.x Signals.Computed)
Import / entryxote (with "-open Xote": Computed.*), also xote/computed
First stable versionComputed.make and Computed.dispose are in 7.1.0 stable (and earlier)
Changes in 7.2.0None
Requires @xote.component (PPX)No

Rules

  1. Computed.make(fn) calls fn synchronously during make, under tracking. Every Signal.get in that call becomes a dependency. If fn throws, make throws and no computed is created.
  2. The result is a Signal.t<'a>. Read it with Signal.get (tracked) or Signal.peek (untracked), anywhere a signal is accepted, including as a dependency of another computed.
  3. When a dependency changes, the computed is marked dirty; fn is not called yet. It is recomputed when read (get or peek) while dirty. Several writes before a read cause one recompute.
  4. 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).
  5. 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.
  6. 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.
  7. If fn throws 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 in View.ErrorBoundary (7.2.0), a throw from a reactive leaf reading the computed goes to that boundary.
  8. 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.
  9. Computed.dispose(c) detaches c immediately (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.
  10. A computed has no setter. Signal.set type-checks on it (it is a Signal.t) but MUST NOT be used: the written value is overwritten by the next recompute.
  11. fn MUST be pure: no writes to signals, no DOM access, no network. Side effects belong in effects.

API

NameSignatureBehaviour
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.disposeSignal.t<'a> => unitDetaches the computed from its sources; next read recomputes.
Signal.get / Signal.peekSignal.t<'a> => 'aRead 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)
6
7module Total = {
8 @xote.component
9 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

  1. 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 None
7})

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.

  1. 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.

  1. 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 never
4 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.

  1. 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 run
4 Console.log(Signal.get(doubled))
5 None
6})

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.computed has the same behaviour.
  • Signal.peek on a dirty computed recomputes it.
  • Reading a computed inside Signal.batch returns the up-to-date value; the batch only delays effects.
  • Inside a flush, an effect that depends on a computed declared with ~equals is 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).
  • ~name is 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.make returns Signal.t<'a>; a type error mentioning Signal.t where a plain value is expected means a missing Signal.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 + 1
7 None
8})
9Signal.set(count, 3) // isOdd recomputes to true: equal, effect does not run
10// 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.
  • /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 from src/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 Xote
2
3let count = Signal.make(0)
4let doubled = Computed.make(() => Signal.get(count) * 2)
5
6Console.log(Signal.get(doubled))

See Also