Skip to content

Effects

Run code outside the signal graph, like timers, storage or logging, whenever its inputs change.

docs/learn/effects.md
moduleXote.Effectboundarysrc/Effect.resientryxote · xote/effectversion7.2.0
Raw MarkdownAPI reference

An effect connects signals to the outside world. It runs right away, remembers the signals it read, and runs again when any of them change.

Use effects for browser APIs, timers, network work, logging, or anything else that should happen because state changed. Don't use them to compute values: that's what computeds are for.

Create an effect

Use Effect.run. The function returns None, or Some(cleanup) as shown below. If you need to stop the effect yourself, use Effect.runWithDisposer.

1open Xote
2
3let count = Signal.make(0)
4
5Effect.run(() => {
6 Console.log2("Count:", Signal.get(count))
7 None
8})

What an effect reacts to

Every Signal.get inside the effect subscribes it to that signal. Dependencies are collected again on every run, so below, name and age only matter while showDetails is true.

1let showDetails = Signal.make(false)
2let name = Signal.make("Ada")
3let age = Signal.make(36)
4
5Effect.run(() => {
6 if Signal.get(showDetails) {
7 Console.log2("Name:", Signal.get(name))
8 Console.log2("Age:", Signal.get(age))
9 }
10 None
11})

Clean up after yourself

Return Some(cleanup) to undo what the effect set up. Cleanup runs before the next run and when the effect is disposed. Here, changing intervalMs clears the old interval before starting a new one.

1@val external setInterval: (unit => unit, int) => int = "setInterval"
2@val external clearInterval: int => unit = "clearInterval"
3
4let intervalMs = Signal.make(1000)
5
6Effect.run(() => {
7 let id = setInterval(() => Console.log("tick"), Signal.get(intervalMs))
8 Some(() => clearInterval(id))
9})

Stop an effect

An effect created inside a component stops when the component goes away. To stop one yourself, use Effect.runWithDisposer. It returns a record with a dispose function, which runs any pending cleanup and unsubscribes the effect.

1let disposer = Effect.runWithDisposer(() => {
2 Console.log(Signal.get(count))
3 None
4})
5
6disposer.dispose()

Read without subscribing

To use a value inside an effect without re-running when it changes, use Signal.peek for one read, or Signal.untrack for a whole block.

1let debug = Signal.make(true)
2
3Effect.run(() => {
4 let tracked = Signal.get(count)
5
6 if Signal.peek(debug) {
7 Console.log2("Debug count:", tracked)
8 }
9
10 None
11})

What effects are for

  • Browser APIs: document title, localStorage, media queries, history and scroll state
  • Timers and subscriptions: intervals, event listeners, sockets and observers
  • Synchronization: pushing state into another system
  • Diagnostics: logging, instrumentation and dev-only inspection

Example: auto-save

Track a draft, wait for a pause in typing, and cancel the pending save whenever the draft changes again.

DraftAutoSave.res
1open Xote
2
3@val external setTimeout: (unit => unit, int) => int = "setTimeout"
4@val external clearTimeout: int => unit = "clearTimeout"
5
6let draft = Signal.make("")
7let saveStatus = Signal.make("Start typing to queue a save")
8
9let handleInput = evt => {
10 let target: {"value": string} = (evt->Obj.magic)["target"]
11 Signal.set(draft, target["value"])
12}
13
14Effect.run(() => {
15 let currentDraft = Signal.get(draft)->String.trim
16
17 if currentDraft == "" {
18 Signal.set(saveStatus, "Start typing to queue a save")
19 None
20 } else {
21 Signal.set(saveStatus, "Saving in 600ms")
22
23 let timeoutId = setTimeout(() => {
24 Console.log2("Saving draft:", currentDraft)
25 Signal.set(saveStatus, "Saved")
26 }, 600)
27
28 Some(() => clearTimeout(timeoutId))
29 }
30})

Auto-save Draft

Each input change re-runs the effect, resets the timer, and only saves the latest draft after the pause.

StatusStart typing to queue a save
Recent savesCleanup cancels any pending save before the next run.
No saves yet. Type, pause, and the latest draft will be recorded here.

Effect or computed?

Ask one question: is the result another value, or is it work outside the signal graph?

  • A value derived from other values: use a computed.
  • Talking to something external: use an effect.

Tips

  • Keep each effect focused on one kind of external work, so its cleanup stays obvious.
  • Return cleanup whenever you allocate timers, listeners, requests or subscriptions.
  • Don't use effects to keep derived state in sync. If the output is another value, use a computed.
  • Use Signal.peek and Signal.untrack on purpose: they opt out of tracking.
  • When several writes should trigger one run instead of many, wrap them in a batch. For effects tied to a component's DOM, see Refs and lifecycle.

Summary

An effect is a function that runs immediately, records the signals it reads (tracked), and runs again synchronously whenever one of them changes. It returns None or Some(cleanup); the cleanup runs before the next run and when the effect is disposed. Effects are for work outside the reactive graph (DOM APIs, timers, storage, network, logging). The most important rule: an effect created while a component renders is owned by that component and disposed with it; an effect created anywhere else (module level, event handler, inside another effect, a promise callback) has no owner and lives until you dispose it.

Availability

ItemValue
ModuleXote.Effect (wraps rescript-signals 3.1.x Signals.Effect)
Import / entryxote (with "-open Xote": Effect.*), also xote/effect
First stable versionEffect.run, Effect.runWithDisposer, Effect.disposer are in 7.1.0 stable. Ownership by the rendering component is in 7.1.0
New in 7.2.0Effects run under the Context and View.ErrorBoundary they were created under (failures go to the boundary); View.onMount / View.onCleanup
Requires @xote.component (PPX)No

Rules

  1. Effect.run(fn) calls fn synchronously, under tracking, before returning. Every Signal.get during that call is a dependency.
  2. When any dependency changes (by set/update with a non-equal value, or a dependency computed recomputing and propagating), the effect is queued and runs once in the next flush, which happens synchronously inside the set (or at the end of the outermost Signal.batch).
  3. Dependencies are re-collected on every run; signals not read in the latest run are no longer dependencies.
  4. Before each re-run, the cleanup returned by the previous run (if Some) is called. On disposal, the pending cleanup is called exactly once. A cleanup runs while the effect is re-tracking, so a Signal.get inside a cleanup subscribes the effect to that signal. A cleanup MUST NOT call Signal.get; read with Signal.peek if it needs a value.
  5. fn must return option<unit => unit>: None or Some(cleanup). Returning a value of another type is a compile error.
  6. Ownership. An effect created while a component renders (in the component body, or synchronously during the render) is registered with that component's owner and disposed when the component is removed (its branch switches, its list item is removed, its boundary resets). Since 7.2.0, an effect created inside View.onMount is owned the same way.
  7. An effect created outside any render (module level, an event handler, a setTimeout/promise callback, or inside another effect's function) has no owner. It lives until its disposer is called; Effect.run returns no disposer, so such an effect lives for the rest of the page.
  8. Effect.runWithDisposer(fn) is Effect.run that also returns {dispose}. dispose() runs the pending cleanup, unsubscribes, and drops any queued run; calling it again is a no-op. It is still owned by the rendering component when created during a render.
  9. An effect that writes to a signal it depends on is re-queued within the same flush. If the written value keeps changing, the flush never ends (the page hangs). Writes to signals the effect does not depend on are safe and join the current flush.
  10. Ordering: effects queued in one flush run in ascending level order (effects whose dependencies are deeper computed chains run later). Among effects at the same level, order is not part of the contract; do not rely on it.
  11. Errors: if fn throws on its first run, Effect.run throws. If it throws on a re-run and the effect was created under a View.ErrorBoundary (7.2.0), the boundary shows its fallback. Otherwise the exception propagates out of the Signal.set / update / batch that triggered the flush, the remaining queued effects of that flush do not run, and they run (including a still-queued throwing effect) on the next flush anywhere. Effects MUST NOT throw; catch inside the effect.
  12. Signal.peek and Signal.untrack read without subscribing; Signal.update reads the current value without subscribing.
  13. Effects are not for computing values. If the effect's only job is to set a signal from other signals, use a computed.

API

NameSignatureBehaviour
Effect.run(unit => option<unit => unit>, ~name: string=?) => unitRun now and on every dependency change; owned by the rendering component if created during a render.
Effect.runWithDisposer(unit => option<unit => unit>, ~name: string=?) => Effect.disposerSame, and returns a handle for manual disposal.
Effect.disposer{dispose: unit => unit}dispose() runs the pending cleanup and stops the effect; idempotent.
View.onMount(unit => unit) => unit7.2.0. Runs after the component's DOM is in the document; never on the server; effects created inside are owned by the component.
View.onCleanup(unit => unit) => unit7.2.0. Registers a callback that runs when the component is removed.

Patterns

Timer with cleanup. Use for intervals, timeouts and listeners whose lifetime follows a signal.

1@val external setInterval: (unit => unit, int) => int = "setInterval"
2@val external clearInterval: int => unit = "clearInterval"
3
4let intervalMs = Signal.make(1000)
5let ticks = Signal.make(0)
6Effect.run(() => {
7 let id = setInterval(() => Signal.update(ticks, n => n + 1), Signal.get(intervalMs))
8 Some(() => clearInterval(id))
9})

Effect owned by a component. Use when the work should stop when the component is removed.

1@val external setTimeout: (unit => unit, int) => int = "setTimeout"
2@val external clearTimeout: int => unit = "clearTimeout"
3
4module Autosave = {
5 @xote.component
6 let make = (~draft: Signal.t<string>) => {
7 let status = Signal.make("Saved")
8 Effect.run(() => {
9 let text = Signal.get(draft)
10 Signal.set(status, "Saving…")
11 let id = setTimeout(() => {
12 Console.log2("saved", text)
13 Signal.set(status, "Saved")
14 }, 600)
15 Some(() => clearTimeout(id))
16 })
17 <p> {Signal.get(status)} </p>
18 }
19}

Effect with a manual lifetime. Use for app-level effects created outside components that must be stopped on a condition.

1let online = Signal.make(true)
2let watcher = Effect.runWithDisposer(() => {
3 Console.log2("online:", Signal.get(online))
4 None
5})
6let stopWatching = () => watcher.dispose()

Browser-only work in a server-rendered app. Use View.onMount (7.2.0) or, before 7.2.0, guard with SSRContext.isClient.

1@val external document: Dom.document = "document"
2@set external setTitle: (Dom.document, string) => unit = "title"
3
4module Title = {
5 @xote.component
6 let make = (~title: Signal.t<string>) => {
7 if SSRContext.isClient {
8 Effect.run(() => {
9 setTitle(document, Signal.get(title))
10 None
11 })
12 }
13 View.null()
14 }
15}

Stale-response guard for async work. Use when an effect starts a request whose result must be ignored once inputs change.

1let userId = Signal.make(1)
2let name = Signal.make("")
3let fetchName: int => promise<string> = id => Promise.resolve("user " ++ Int.toString(id))
4
5Effect.run(() => {
6 let stale = ref(false)
7 fetchName(Signal.get(userId))
8 ->Promise.thenResolve(result =>
9 if !stale.contents {
10 Signal.set(name, result)
11 }
12 )
13 ->ignore
14 Some(() => stale := true)
15})

For data loading prefer Resource (7.2.0, /docs/learn/async-data), which implements this guard.

Anti-patterns

  1. Effect as a computed.
1let price = Signal.make(10)
2let quantity = Signal.make(2)
3let total = Signal.make(0)
4Effect.run(() => {
5 Signal.set(total, Signal.get(price) * Signal.get(quantity))
6 None
7})

Symptom: an extra signal that can drift (anyone can set it), stale values inside a batch. Fix:

1let price = Signal.make(10)
2let quantity = Signal.make(2)
3let total = Computed.make(() => Signal.get(price) * Signal.get(quantity))
  1. Creating an effect inside an effect.
1let section = Signal.make("home")
2let scroll = Signal.make(0)
3Effect.run(() => {
4 let _ = Signal.get(section)
5 Effect.run(() => { // not owned by the outer effect
6 Console.log(Signal.get(scroll))
7 None
8 })
9 None
10})

Symptom: every change to section adds one more inner effect; all of them keep running (duplicate logs, leaked listeners). Fix: create the inner effect once, or use runWithDisposer and dispose it from the outer effect's cleanup.

1let section = Signal.make("home")
2let scroll = Signal.make(0)
3Effect.run(() => {
4 let _ = Signal.get(section)
5 let inner = Effect.runWithDisposer(() => {
6 Console.log(Signal.get(scroll))
7 None
8 })
9 Some(() => inner.dispose())
10})
  1. Subscribing to what you write.
1let count = Signal.make(0)
2Effect.run(() => {
3 Signal.set(count, Signal.get(count) + 1)
4 None
5})

Symptom: the page hangs (rule 9). Fix: do the write in an event handler, or use Signal.update plus a condition so the value settles.

  1. Effect in an event handler.
1let query = Signal.make("")
2let onFocus = (_: Dom.event) =>
3 Effect.run(() => { // new, unowned effect on every focus
4 Console.log(Signal.get(query))
5 None
6 })

Symptom: one more effect per event, never disposed. Fix: create the effect once (component body or module level) and let the handler only write signals.

  1. Missing cleanup.
1@val external setInterval: (unit => unit, int) => int = "setInterval"
2let rate = Signal.make(1000)
3Effect.run(() => {
4 let _ = setInterval(() => Console.log("tick"), Signal.get(rate))
5 None
6})

Symptom: each change to rate starts another interval; old ones never stop. Fix: return Some(() => clearInterval(id)) (see Patterns).

Edge cases

  • An effect body that reads no signals runs once and never again; it is still owned (and its cleanup run on disposal) when created during a render.
  • Signal.set inside an effect does not flush immediately; it joins the current flush.
  • Disposing an effect that is already queued drops the queued run (rescript-signals 3.1.3+); the cleanup still runs exactly once.
  • A component body runs once and untracked; an effect inside it is the only way that component reacts to signals outside its JSX.
  • ~name is a debugging label stored on the effect; Xote does not read it.
  • Effects run synchronously inside the triggering set; long work in an effect blocks the write. Defer heavy work with setTimeout from the effect (and clear it in cleanup).

SSR and hydration

  • Effect.run has no server guard. An effect created while SSR.renderToString / SSR.renderDocument renders a component runs once on the server, and it is not disposed when the render ends: it stays subscribed to the signals it read. In a long-running server, effects that read module-level signals therefore leak and react to later writes. Guard browser-only effects with SSRContext.isClient, or create them in View.onMount (7.2.0), which never runs on the server.
  • During hydration the component bodies run again on the client, so client effects are created then; nothing is transferred from the server's effects.
  • Resources (7.2.0) do not fetch during a server render; prefer them over effects for data.

Verify

  • A compile error saying This has type: unit where option<unit => unit> is expected means the effect function did not end with None / Some(cleanup).
  • Ownership check in jsdom: mount a component that creates an effect, remove it (toggle a condition), write the dependency, and assert the effect did not run and its cleanup ran once.
  • Minimal behaviour check:
1let n = Signal.make(0)
2let log = []
3let handle = Effect.runWithDisposer(() => {
4 let v = Signal.get(n)
5 log->Array.push("run " ++ Int.toString(v))->ignore
6 Some(() => log->Array.push("cleanup " ++ Int.toString(v))->ignore)
7})
8Signal.set(n, 1)
9handle.dispose()
10handle.dispose() // no-op
11Signal.set(n, 2) // no run
12// log == ["run 0", "cleanup 0", "run 1", "cleanup 1"]
  • /docs/learn/computeds — use instead of effects that only derive values.
  • /docs/learn/lifecycle — View.onMount, View.onCleanup, error boundaries (7.2.0).
  • /docs/learn/async-data — Resource for data loading with built-in staleness handling.
  • /docs/advanced/batching — how several writes collapse into one effect run.
  • /docs/advanced/ssr — server rendering, SSRContext.isClient.
  • /docs/api/effect — full reference from src/Effect.resi.
  • /docs/glossary — terms used on this page.

API reference

This page lists the supported API for the Effect module.

Effect

Effect runs side effects when the signals it reads change.

Effect.disposer

1type disposer = {dispose: unit => unit}

A manual teardown handle returned by Effect.runWithDisposer.

Effect.run

1let run: (
2 unit => option<unit => unit>,
3 ~name: option<string>=?,
4) => unit

Run an effect immediately, then re-run it whenever tracked dependencies change. Return Some(cleanup) to clean up before the next run, or None when no cleanup is needed.

Effect.runWithDisposer

1let runWithDisposer: (
2 unit => option<unit => unit>,
3 ~name: option<string>=?,
4) => Effect.disposer

Run an effect and return a disposer for explicit teardown.

Example

1open Xote
2
3let count = Signal.make(0)
4
5let disposer = Effect.runWithDisposer(() => {
6 Console.log2("count", Signal.get(count))
7 None
8})
9
10disposer.dispose()

See Also