Signals
Hold a value, read it, change it, and let everything that depends on it follow.
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, andEffectfrom 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 Xote23let 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")34let 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)45 Console.log2("Tracked count:", tracked)6 Console.log2("Current theme:", snapshot.theme)7 None8})
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)23Signal.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)23Signal.set(count, 5) // No update4Signal.set(count, 6) // Notifies dependents56let 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}23let position = Signal.make(4 {x: 0, y: 0},5 ~equals=(a, b) => a.x == b.x && a.y == b.y,6)78Signal.set(position, {x: 0, y: 0}) // No update9Signal.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)45let 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.
1open Xote23let count = Signal.make(0)45let increment = (_evt: Dom.event) => {6 Signal.update(count, n => n + 1)7}89let decrement = (_evt: Dom.event) => {10 Signal.update(count, n => n - 1)11}1213let reset = (_evt: Dom.event) => {14 Signal.set(count, 0)15}1617@xote.component18let 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}2627// in App.res (the entry point — a module can't reference28// itself by its own file name):29// View.mountById(<Counter />, "app")Counter
Tips
- Keep each signal focused on one job. A small record is fine; a grab bag of unrelated state is not.
- Prefer
Signal.updatewhen the next value depends on the current one. - Treat
Signal.peekas 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
| Item | Value |
|---|---|
| Module | Xote.Signal (re-export of rescript-signals 3.1.x Signals.Signal) |
| Import / entry | xote (with "-open Xote": Signal.*), also xote/signal |
| First stable version | All functions on this page are in 7.1.0 stable (and earlier) |
| Changes in 7.2.0 | None |
Requires @xote.component (PPX) | No. The PPX only changes how reads inside JSX become reactive leaves |
Rules
Signal.make(v)creates a signal holdingv. It has no owner: a signal is plain data and is never disposed; it is garbage-collected when unreachable.Signal.get(s)returns the current value. Inside a tracking scope (computed function, effect function, reactive leaf,View.trackedblock, resource fetch before its firstawait) it recordssas a dependency of that scope. Outside any tracking scope it is a plain read.Signal.peek(s)returns the current value and never records a dependency.Signal.untrack(fn)runsfnwith dependency recording disabled for every read inside it and returnsfn's result.Signal.set(s, v)comparesvwith the current value using the signal's equality function (default: JavaScript strict equality===; replaced by~equalsatmake). If they are equal,setdoes nothing: no write, no notification.- If the equality function throws, the value is treated as changed.
- When the value changed,
setstores it, marks dependent computeds dirty (transitively) and queues dependent effects, then flushes the queue synchronously: queued effects run beforesetreturns. - Inside
Signal.batch(fn), or while the scheduler is already flushing (for example asetinside an effect), the flush is deferred to the end of the outermost batch / the current flush. The written value is visible immediately togetandpeek. Signal.update(s, f)isSignal.set(s, f(current)). It reads the current value without recording a dependency, so calling it inside an effect does not subscribe the effect tos.- 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.
- 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.
- Equality is on the value as stored. Mutating an object/array in place and calling
setwith the same reference is a no-op under the default equality (same reference===). Always write a new value. ~nameis a debugging label stored on the cell (visible in a debugger as the record'snamefield). Xote 7.x does not read it; no warning or devtool output uses it.Signal.t<'a>is abstract. A computed is also aSignal.t<'a>and type-checks withset/update; see Anti-patterns for why you MUST NOT write to a computed.
API
| Name | Signature | Behaviour |
|---|---|---|
Signal.make | ('a, ~name: string=?, ~equals: ('a, 'a) => bool=?) => Signal.t<'a> | New signal; ~equals decides whether set notifies. |
Signal.get | Signal.t<'a> => 'a | Read; tracked inside a tracking scope. |
Signal.peek | Signal.t<'a> => 'a | Read; never tracked. Recomputes a dirty computed first. |
Signal.set | (Signal.t<'a>, 'a) => unit | Write; no-op if equal; flushes dependents synchronously unless batching. |
Signal.update | (Signal.t<'a>, 'a => 'a) => unit | set(s, f(current)); does not subscribe the caller. |
Signal.batch | (unit => 'a) => 'a | Defers the flush until the outermost batch returns; returns fn's result. |
Signal.untrack | (unit => 'a) => 'a | Runs 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.res2let 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.component3 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) // dependency5 let size = Signal.peek(pageSize) // not a dependency6 Console.log2(q, size)7 None8})
Anti-patterns
- Mutating in place.
1let items = Signal.make([1, 2])2let add = n => {3 let current = Signal.peek(items)4 current->Array.push(n)->ignore5 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.
- Caching a read in the component body.
1let count = Signal.make(0)2module Label = {3 @xote.component4 let make = () => {5 let value = Signal.get(count) // component body: runs once, untracked6 <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.component4 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.
setfromgetinside an effect.
1let count = Signal.make(0)2Effect.run(() => {3 Signal.set(count, Signal.get(count) + 1) // subscribes to count, then changes it4 None5})
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.
- 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.
- Passing a value where a signal is needed.
1module Badge = {2 @xote.component3 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.component3 let make = (~count: Signal.t<int>) => <span> {Signal.get(count)} </span>4}
Edge cases
peekandgeton a dirty computed both recompute it first;peekjust does not subscribe.- A
setinside an effect does not flush immediately; it joins the current flush. Code after thesetinside the same effect runs before other effects react. Signal.batchthat 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/batchcall 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. ~equalsis called with(current, next). It is also used when the signal is written withupdate.- There is no
subscribeAPI. To react to a signal outside the view, useEffect.run/Effect.runWithDisposer. - Signals are synchronous: there is no microtask delay between
setand 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 meansSignal.getis 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))->ignore5 None6})7Signal.set(count, 1)8Signal.set(count, 1) // equal: no run9// seen == [0, 1]
- In the browser: a leaf that reads the signal must change immediately after the write (synchronously), without any
await.
Related
/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 fromsrc/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 Xote23let count = Signal.make(0)45let increment = () => {6 Signal.update(count, n => n + 1)7}89let current = Signal.peek(count)