Skip to content

Signals

Hold a value, read it, change it, and let everything that depends on it follow.

docs/learn/signals.md
moduleXote.Signalboundarysrc/Signal.resientryxote · xote/signalversion7.2.0
Raw MarkdownAPI reference

A signal holds a piece of state. It remembers who reads it and tells them when its value actually changes. Most Xote state starts as a signal.

Info: Xote re-exports Signal, Computed, and Effect from rescript-signals.

Create a signal

Use Signal.make with a starting value. Optionally pass ~name for debugging, and ~equals when the default equality check isn't what you want.

1open Xote
2
3let count = Signal.make(0)
4let userName = Signal.make("Ada", ~name="user-name")
5let settings = Signal.make({
6 theme: "dark",
7 compact: false,
8})

Read a signal

There are two ways to read. Pick based on whether the code should run again when the signal changes.

Signal.get: read and subscribe

Use Signal.get inside a computed, an effect, or a component's JSX. That code re-runs whenever the signal changes.

1let firstName = Signal.make("Ada")
2let lastName = Signal.make("Lovelace")
3
4let fullName = Computed.make(() =>
5 `${Signal.get(firstName)} ${Signal.get(lastName)}`
6)

Signal.peek: read without subscribing

Use Signal.peek when you need the current value but don't want to react to changes. It's handy for logging, snapshots, and one-off reads inside effects.

1Effect.run(() => {
2 let tracked = Signal.get(count)
3 let snapshot = Signal.peek(settings)
4
5 Console.log2("Tracked count:", tracked)
6 Console.log2("Current theme:", snapshot.theme)
7 None
8})

Update a signal

Signal.set: replace the value

Use Signal.set when you already know the next value.

1Signal.set(count, 10)
2Signal.set(userName, "Grace")

Signal.update: change it based on the current value

Use Signal.update when the next value depends on the current one. The intent stays obvious and you skip an extra read.

1Signal.update(count, n => n + 1)
2
3Signal.update(settings, current => {...current,
4 compact: !current.compact,
5})

When a signal notifies

A signal only notifies its dependents when the new value is different from the current one. By default "different" means JavaScript strict equality, ===.

Default equality

Setting a primitive to the same value does nothing. For arrays, records and objects, a new reference counts as a change, even if the contents look the same.

1let count = Signal.make(5)
2
3Signal.set(count, 5) // No update
4Signal.set(count, 6) // Notifies dependents
5
6let items = Signal.make([1, 2, 3])
7Signal.set(items, [1, 2, 3]) // New array reference, so this updates

Custom equality

To compare compound data by value, pass ~equals to Signal.make.

1type position = {x: int, y: int}
2
3let position = Signal.make(
4 {x: 0, y: 0},
5 ~equals=(a, b) => a.x == b.x && a.y == b.y,
6)
7
8Signal.set(position, {x: 0, y: 0}) // No update
9Signal.set(position, {x: 0, y: 1}) // Update

How dependencies are tracked

Every Signal.get inside a running computed or effect becomes a dependency. Before each re-run the dependencies are cleared and collected again, so they follow your control flow. Below, temperature only depends on fahrenheit while useMetric is false.

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: counter

Most Xote state starts like this: a signal, a few updates, and a read in the UI.

Counter.res
1open Xote
2
3let count = Signal.make(0)
4
5let increment = (_evt: Dom.event) => {
6 Signal.update(count, n => n + 1)
7}
8
9let decrement = (_evt: Dom.event) => {
10 Signal.update(count, n => n - 1)
11}
12
13let reset = (_evt: Dom.event) => {
14 Signal.set(count, 0)
15}
16
17@xote.component
18let make = () => {
19 <div>
20 <h1> {"Count: "} {Signal.get(count)} </h1>
21 <button onClick={decrement}> {"-"} </button>
22 <button onClick={reset}> {"Reset"} </button>
23 <button onClick={increment}> {"+"} </button>
24 </div>
25}
26
27// in App.res (the entry point — a module can't reference
28// itself by its own file name):
29// View.mountById(<Counter />, "app")
Signal state

Counter

Neutral
0
Current Count
One writable signal updates the UI immediately when the value changes.

Tips

  • Keep each signal focused on one job. A small record is fine; a grab bag of unrelated state is not.
  • Prefer Signal.update when the next value depends on the current one.
  • Treat Signal.peek as a snapshot tool, not your default way to read.
  • Add custom equality only when strict equality causes real noise in the UI or in effects.
  • If a value can be worked out from other signals, don't store it in its own signal: derive it with a computed. To connect signals to timers, requests or browser APIs, use an effect.

Summary

A signal (Signal.t<'a>) is a writable reactive cell. Signal.get returns its value and, inside a tracking scope, records it as a dependency; Signal.set / Signal.update write it and, when the value changed by the signal's equality function, re-run every dependent effect synchronously, before the write returns (unless inside Signal.batch or an in-progress flush). The rule that matters most: read with Signal.get where the value is used (JSX, computed, effect), never cache it in a component body.

Availability

ItemValue
ModuleXote.Signal (re-export of rescript-signals 3.1.x Signals.Signal)
Import / entryxote (with "-open Xote": Signal.*), also xote/signal
First stable versionAll functions on this page are in 7.1.0 stable (and earlier)
Changes in 7.2.0None
Requires @xote.component (PPX)No. The PPX only changes how reads inside JSX become reactive leaves

Rules

  1. Signal.make(v) creates a signal holding v. It has no owner: a signal is plain data and is never disposed; it is garbage-collected when unreachable.
  2. Signal.get(s) returns the current value. Inside a tracking scope (computed function, effect function, reactive leaf, View.tracked block, resource fetch before its first await) it records s as a dependency of that scope. Outside any tracking scope it is a plain read.
  3. Signal.peek(s) returns the current value and never records a dependency. Signal.untrack(fn) runs fn with dependency recording disabled for every read inside it and returns fn's result.
  4. Signal.set(s, v) compares v with the current value using the signal's equality function (default: JavaScript strict equality ===; replaced by ~equals at make). If they are equal, set does nothing: no write, no notification.
  5. If the equality function throws, the value is treated as changed.
  6. When the value changed, set stores it, marks dependent computeds dirty (transitively) and queues dependent effects, then flushes the queue synchronously: queued effects run before set returns.
  7. Inside Signal.batch(fn), or while the scheduler is already flushing (for example a set inside an effect), the flush is deferred to the end of the outermost batch / the current flush. The written value is visible immediately to get and peek.
  8. Signal.update(s, f) is Signal.set(s, f(current)). It reads the current value without recording a dependency, so calling it inside an effect does not subscribe the effect to s.
  9. Each queued effect runs at most once per flush, even if several of its dependencies changed. Effects are run in ascending "level" order: an effect whose dependencies include computeds that depend on other computeds runs after effects with shallower dependencies. Do not rely on the relative order of sibling effects.
  10. Reads are glitch-free: a computed read during a flush is recomputed on read if any of its sources changed, so an effect never observes a computed that is out of date relative to the signals it was derived from.
  11. Equality is on the value as stored. Mutating an object/array in place and calling set with the same reference is a no-op under the default equality (same reference ===). Always write a new value.
  12. ~name is a debugging label stored on the cell (visible in a debugger as the record's name field). Xote 7.x does not read it; no warning or devtool output uses it.
  13. Signal.t<'a> is abstract. A computed is also a Signal.t<'a> and type-checks with set/update; see Anti-patterns for why you MUST NOT write to a computed.

API

NameSignatureBehaviour
Signal.make('a, ~name: string=?, ~equals: ('a, 'a) => bool=?) => Signal.t<'a>New signal; ~equals decides whether set notifies.
Signal.getSignal.t<'a> => 'aRead; tracked inside a tracking scope.
Signal.peekSignal.t<'a> => 'aRead; never tracked. Recomputes a dirty computed first.
Signal.set(Signal.t<'a>, 'a) => unitWrite; no-op if equal; flushes dependents synchronously unless batching.
Signal.update(Signal.t<'a>, 'a => 'a) => unitset(s, f(current)); does not subscribe the caller.
Signal.batch(unit => 'a) => 'aDefers the flush until the outermost batch returns; returns fn's result.
Signal.untrack(unit => 'a) => 'aRuns fn with all reads untracked; returns its result.

Patterns

Module-level state shared by the whole app. Use when one value is shared everywhere (current user, theme).

1// Session.res
2let currentUser: Signal.t<option<string>> = Signal.make(None)
3let signIn = name => Signal.set(currentUser, Some(name))
4let signOut = () => Signal.set(currentUser, None)

Component-local state. Use when each instance needs its own value; create it in the component body.

1module Counter = {
2 @xote.component
3 let make = () => {
4 let count = Signal.make(0)
5 <button onClick={_ => Signal.update(count, n => n + 1)}>
6 {"Clicked "}
7 {Signal.get(count)}
8 </button>
9 }
10}

Derived update from the current value. Use update (not set(s, get(s) + 1)) so the caller never subscribes by accident.

1let todos = Signal.make(["write docs"])
2let add = text => Signal.update(todos, list => Array.concat(list, [text]))
3let remove = index => Signal.update(todos, list => list->Array.filterWithIndex((_, i) => i != index))

Structural equality for records/arrays. Use when equal-by-value writes should not notify.

1type point = {x: int, y: int}
2let position = Signal.make({x: 0, y: 0}, ~equals=(a, b) => a.x == b.x && a.y == b.y)
3Signal.set(position, {x: 0, y: 0}) // equal: no dependent runs

Read a value without subscribing. Use when an effect needs a value but must not re-run when it changes.

1let query = Signal.make("")
2let pageSize = Signal.make(20)
3Effect.run(() => {
4 let q = Signal.get(query) // dependency
5 let size = Signal.peek(pageSize) // not a dependency
6 Console.log2(q, size)
7 None
8})

Anti-patterns

  1. Mutating in place.
1let items = Signal.make([1, 2])
2let add = n => {
3 let current = Signal.peek(items)
4 current->Array.push(n)->ignore
5 Signal.set(items, current) // same reference: equal under ===
6}

Symptom: the array changes but nothing on the page updates and no effect runs. Fix: write a new value.

1let items = Signal.make([1, 2])
2let add = n => Signal.update(items, list => Array.concat(list, [n]))

Why: rule 11. Equality is checked on the reference.

  1. Caching a read in the component body.
1let count = Signal.make(0)
2module Label = {
3 @xote.component
4 let make = () => {
5 let value = Signal.get(count) // component body: runs once, untracked
6 <span> {value} </span>
7 }
8}

Symptom: the label shows the initial value forever. Fix: read in the JSX.

1let count = Signal.make(0)
2module Label = {
3 @xote.component
4 let make = () => <span> {Signal.get(count)} </span>
5}

Why: the component body is not a tracking scope; the PPX turns reads in JSX into reactive leaves, not reads in the body.

  1. set from get inside an effect.
1let count = Signal.make(0)
2Effect.run(() => {
3 Signal.set(count, Signal.get(count) + 1) // subscribes to count, then changes it
4 None
5})

Symptom: the effect re-runs after each of its own writes; with a value that always changes it never settles (an unbounded loop that hangs the page). Fix: use update (untracked read) and make the write conditional, or move the logic out of the effect (event handler, computed).

1let count = Signal.make(0)
2let increment = () => Signal.update(count, n => n + 1) // call from an event handler

Why: rules 2, 6, 7. An effect that writes a signal it depends on is re-queued in the same flush.

  1. Writing to a computed.
1let base = Signal.make(1)
2let doubled = Computed.make(() => Signal.get(base) * 2)
3Signal.set(doubled, 100) // type-checks

Symptom: dependents briefly see 100, then the next change to base silently replaces it with the computed value. Fix: write the source signal (Signal.set(base, 50)), or make the value a plain signal if it is user-editable.

Why: a computed is a Signal.t for reading; its value is owned by its function.

  1. Passing a value where a signal is needed.
1module Badge = {
2 @xote.component
3 let make = (~count: int) => <span> {count} </span>
4}
5// <Badge count={Signal.get(total)} /> — evaluated once at the call site

Symptom: the badge never updates. Fix: type the prop as Signal.t<int> (or MaybeSignal.t<int>) and read it inside.

1module Badge = {
2 @xote.component
3 let make = (~count: Signal.t<int>) => <span> {Signal.get(count)} </span>
4}

Edge cases

  • peek and get on a dirty computed both recompute it first; peek just does not subscribe.
  • A set inside an effect does not flush immediately; it joins the current flush. Code after the set inside the same effect runs before other effects react.
  • Signal.batch that throws: the exception propagates, and effects queued by writes inside it are not run at that point; they run on the next flush caused by any later write anywhere. Do not throw inside a batch; validate before writing, so a batch either completes or writes nothing.
  • An effect that throws during a flush (outside an error boundary) propagates out of the set/update/batch call that triggered the flush, and effects queued after it in that flush do not run then. They (and the throwing effect, if still queued) run on the next flush. Do not let effects throw; see the Effects page.
  • ~equals is called with (current, next). It is also used when the signal is written with update.
  • There is no subscribe API. To react to a signal outside the view, use Effect.run / Effect.runWithDisposer.
  • Signals are synchronous: there is no microtask delay between set and the DOM update of the reactive leaves that read it.

SSR and hydration

  • During SSR.renderToString / SSR.renderDocument, reactive leaves read signals once at their current value; there is no later update on the server.
  • Module-level signals in a server process are shared by every request. Request-specific state MUST be created inside the rendered component tree (or passed through Context), not at module level.
  • To carry a server value to the client, use SSRState (see /docs/advanced/ssr); hydration does not transfer signal values by itself.

Verify

  • Type errors: This has type: int But it's expected to have type: Signal.t<int> means a value was passed where a signal is required (anti-pattern 5); the reverse means Signal.get is missing.
  • A minimal behaviour check (Node, no DOM needed):
1let count = Signal.make(0)
2let seen = []
3Effect.run(() => {
4 seen->Array.push(Signal.get(count))->ignore
5 None
6})
7Signal.set(count, 1)
8Signal.set(count, 1) // equal: no run
9// seen == [0, 1]
  • In the browser: a leaf that reads the signal must change immediately after the write (synchronously), without any await.
  • /docs/learn/computeds — derive values from signals instead of copying them into other signals.
  • /docs/learn/effects — the only way to react to a signal outside the view; owner and cleanup rules.
  • /docs/advanced/batching — group several writes into one flush.
  • /docs/thinking-in-signals — the component-runs-once model behind rule 2.
  • /docs/api/signal — full reference with doc comments from src/Signal.resi.
  • /docs/glossary — terms used on this page.

API reference

This page lists the supported API for the Signal module.

Signal

Signal stores writable reactive state. Read it with Signal.get when you want dependency tracking, or Signal.peek when you want a snapshot.

Signal.t

1type t<'a>

A signal value containing state of type 'a.

Signal.make

1let make: (
2 'a,
3 ~name: option<string>=?,
4 ~equals: option<('a, 'a) => bool>=?,
5) => Signal.t<'a>

Create a signal with an initial value. ~name is for debugging, and ~equals replaces the default JavaScript strict equality check.

Signal.get

1let get: Signal.t<'a> => 'a

Read the current value and subscribe the active computed or effect, if one exists.

Signal.peek

1let peek: Signal.t<'a> => 'a

Read the current value without creating a dependency.

Signal.set

1let set: (Signal.t<'a>, 'a) => unit

Replace the signal value. Dependents are notified only when the equality check says the value changed.

Signal.update

1let update: (Signal.t<'a>, 'a => 'a) => unit

Compute the next value from the current value.

Signal.batch

1let batch: (unit => 'a) => 'a

Run several writes as one scheduler flush. The callback result is returned.

Signal.untrack

1let untrack: (unit => 'a) => 'a

Run a block without dependency capture.

Example

1open Xote
2
3let count = Signal.make(0)
4
5let increment = () => {
6 Signal.update(count, n => n + 1)
7}
8
9let current = Signal.peek(count)

See Also