# Effects, bindings and bridges

> Push reactive state to external targets, single-source writers, and peer graphs.

Use an effect, a binding, or a cross-graph bridge when reactive state needs to drive external work
rather than produce a cached value for downstream readers (for derived values, see
[Memos and computation expressions](memos-and-ce.md)).

## Effects

`effect`{fsharp} connects reactive inputs to side effects such as logging, DOM mutations, or
external subscriptions. With Phase-1 `let!`{fsharp} / `and!`{fsharp} binds, the compiler builds a
static split effect (`EffectOn`{fsharp}): Phase 1 reads and compares the settled key, and Phase 2
runs untracked inside an owning scope only when that key moves.

```fsharp
open Ranvier
open Ranvier.CE

let attachSubscription (channel: Signal<string>) (page: Signal<int>) (subscribe: string -> int -> System.IDisposable) =
    effect {
        let! name = channel |> withComparer System.StringComparer.OrdinalIgnoreCase
        and! number = page
        let sub = subscribe name number
        cleanup { sub.Dispose () }
    }
```

Choose the `effect`{fsharp} shape that matches your dependency structure:

- **Static Phase-1 key (`let! ... and! ...`{fsharp}):** resolves `source.Graph`{fsharp} directly
  without `graph.Activate ()`{fsharp}. See
  [The graph — Graph inference](graph.md#graph-inference).

- **When the action runs:** an equal key (under the graph policy or `withComparer cmp`{fsharp}), a
  `Pending`{fsharp} input, or a `Failed`{fsharp} input leaves the previous Phase-2 action and its
  cleanups in place.

- **Timing:** add `debounce`{fsharp} or `throttle*`{fsharp} in the header to gate rapid key bursts
  (see [Equality, buffers and timing](equality-and-timing.md#debounce-and-throttle)).

- **Dynamic reads:** sequential `let!`{fsharp} chains (`let! k = a`{fsharp} followed by
  `let! v = lookup k`{fsharp}) or bindless `effect { ... }`{fsharp} / `createEffect`{fsharp}
  re-collect dependencies dynamically on each run.

- **Previous values:** `effect`{fsharp} has no `previous`{fsharp} token. When an action needs
  `(prev, current)`{fsharp} deltas, compute them upstream with `memo.previous`{fsharp} or
  `memo.previousOr seed`{fsharp} in a `memo`{fsharp}.

### Flush timing, cleanups, and handles

Outside a batch or an active flush, an effect runs immediately on creation, and writes flush
dependent effects synchronously before `signal.Value <- v`{fsharp} returns.[^flush-clean] Inside
`batched { ... }`{fsharp}, woken effects wait until the outermost batch exits (see
[Lifetimes and scopes](lifetimes.md)).

- **Cleanups (`cleanup { ... }`{fsharp} / `onCleanup`{fsharp}):** registered LIFO on the current
  run's [scope](lifetimes.md), running untracked before the next action run and when the enclosing
  owner is disposed.[^disposed-effect]

- **Inspection handle:** `effect`{fsharp} returns `unit`{fsharp} by default. Add the
  `node`{fsharp} header (`effect { node; ... }`{fsharp}, or `createEffectNode`{fsharp}) to obtain
  an `INode`{fsharp} for inspecting `Id`{fsharp} and `Status`{fsharp} (such as
  `Status.Stale`{fsharp} inside a batch).

- **Effect instance:** construct `new Effect (graph, body)`{fsharp} when you need `Runs`{fsharp},
  `Error`{fsharp}, or independent `Dispose ()`{fsharp}.

- **Feedback writes:** an effect that writes a signal it reads re-runs in the active flush until
  the value converges.[^feedback-writes]

:::warning Contained effect errors
An unhandled exception in an effect body is stored in `Effect.Error`{fsharp} and marks
`Status.Error`{fsharp}. It does **not** escape `signal.Value <- v`{fsharp} or `flush ()`{fsharp},
and sibling effects queued in the same flush still run.[^effect-errors]

Inspect `Effect.Error`{fsharp}, `graph.Root.Errors`{fsharp}, or
[Tracing and journal](tracing-and-journal.md) when testing for failures.
:::

## One-source bindings

When a view property or external sink copies a single `Signal<'T>`{fsharp} or `Memo<'T>`{fsharp}
on the same graph, `bindSignal source target write`{fsharp} and
`bindMemo source target write`{fsharp} attach a fixed single-edge observer in $O(1)$ without
dynamic source-list tracking:[^direct-link]

```fsharp
open Ranvier
open Ranvier.CE

type Label () =
    member val Text = "" with get, set

let wireLabel (g: Graph) =
    g {
        let name = signal { return "Ada" }
        let label = Label ()
        bindSignal name label (fun target value -> target.Text <- value)
        name.Value <- "Grace"
        return label.Text // "Grace"
    }
```

- **Untracked leaf writer:** `write`{fsharp} runs untracked on the next flush (coalescing multiple
  writes inside a `batched`{fsharp} block into one write of the latest value) and must not create
  reactive nodes or register cleanups.

- **Equality cutoff:** `source`{fsharp}'s equality policy or per-node comparer suppresses equal
  writes before `write`{fsharp} runs.[^binding-cutoff]

- **Unready memos:** while a `Memo<'T>`{fsharp} is `Pending`{fsharp} or `Failed`{fsharp},
  `target`{fsharp} retains its last written value.

- **Lifetime:** disposed automatically with the enclosing owner.[^direct-unlink]

Compare effect and binding workloads in [Benchmarks → Effects](../benchmarks/effects.md).

## Cross-graph bridges

A worker graph can forward derived state to a `Signal<'T>`{fsharp} on another graph or thread
without allocating per-event closures. For a write-only target, obtain a `SignalPort<'T>`{fsharp}
with `target.CreatePort ()`{fsharp} or `Signal.createPort target`{fsharp}.

### Forward one source

`bindSignalTo source target`{fsharp} (`SignalPort.bindSignal source port`{fsharp}) and
`bindMemoTo source target`{fsharp} (`SignalPort.bindMemo source port`{fsharp}) resolve
`source.Graph`{fsharp} directly without `Activate ()`{fsharp}. See
[The graph — Graph inference](graph.md#graph-inference).

The forwarders ignore `Pending`{fsharp} / `Failed`{fsharp} / equal memo states, and coalesce
off-thread bursts in $O(1)$ time and `0 B` steady-state memory.

### Project multiple sources

Use `bridge target { ... }`{fsharp} to combine tracked Phase-1 inputs (`let!`{fsharp},
`and!`{fsharp}, `withComparer`{fsharp}, `tryRead`{fsharp}) with a Phase-2 projection that runs
with tracking closed.

- **Input cutoff:** an equal Phase-1 key skips the projection.

- **Output cutoff:** before posting, the bridge compares the projected value using
  `comparer cmp`{fsharp} or the source graph's equality policy.[^bridge-cutoff] Equal outputs
  leave the target dispatcher asleep.

- **Timing:** `debounce`{fsharp} and `throttle*`{fsharp} headers rate-limit Phase-1 bursts on the
  source graph. Use `clock`{fsharp} to supply a clock.

- **Inspection:** the `node`{fsharp} header returns the bridge as an `INode`{fsharp}.

```fsharp
let connectWorker (workerA: Signal<int>) (workerB: Signal<int>) (uiSummary: SignalPort<string>) =
    bridge uiSummary {
        comparer System.StringComparer.Ordinal
        throttleLast (System.TimeSpan.FromMilliseconds 16.)
        let! a = workerA
        and! b = workerB
        return $"total = {a + b}"
    }
```

For FIFO ordered commands or multi-signal atomic transactions across threads, use
`dispatch`{fsharp} instead; see
[Streams, threading and multi-graph dispatch](streams-and-threading.md#choosing-a-cross-thread-or-cross-graph-primitive).

### Watch cross-graph cutoff on the signal map

`worker`{fsharp} runs as a separate peer graph feeding `uiTick`{fsharp} through `gate`{fsharp}.
Press **Minor tick (14)** to see Phase 2 project `14 / 10 = 1`{fsharp} and suppress the
cross-graph post; press **Next bucket (23)** to see `2`{fsharp} surge across the dashed bridge
link into `uiTick`{fsharp}:

<div class="rv-map-card">

```fsharp
let worker = peerGraph "worker"
let rawTick = Trace.named "rawTick" (fun () -> worker { return signal { return 10 } })
let uiTick = signal { return 0 }
let gate =
    bridge uiTick {
        node
        let! x = rawTick
        return x / 10
    }
let label =
    memo {
        let! b = uiTick
        return $"Bucket {b}"
    }
effect {
    let! s = label
    printfn "%s" s
}

controls [
    button "Minor tick (14)" (fun () -> rawTick.Value <- 14)
    |> describe "Bucket stays 1: bridge suppresses the cross-graph post."
    |> expect "uiTick stays at 1" (fun () -> uiTick.Peek = 1 && label.Peek = "Bucket 1")
    button "Next bucket (23)" (fun () -> rawTick.Value <- 23)
    |> describe "Bucket moves to 2: bridge surges across the dashed graph link."
    |> expect "uiTick updates to 2" (fun () -> uiTick.Peek = 2 && label.Peek = "Bucket 2")
]
```

<div class="rv-map-host" id="rvm-p597376da97-c1" data-ranvier-map-page="p597376da97" data-ranvier-map-cell="c1"></div>

</div>


[^flush-clean]: [`flush_returns_clean`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#flush_returns_clean), [`queued_at_most_once_new_graph`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#queued_at_most_once_new_graph), [`heap_flush_returns_clean`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Heap.Scheduler.html#heap_flush_returns_clean).
[^disposed-effect]: [`disposed_effect_never_runs`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#disposed_effect_never_runs), [`queued_effect_disposed_skipped`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Ownership.html#queued_effect_disposed_skipped).
[^feedback-writes]: [`flush_reruns_dirty`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#flush_reruns_dirty), [`marks_survive_body_end`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Runs.html#marks_survive_body_end).
[^effect-errors]: [`body_failure_contained`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#body_failure_contained), [`drain_continues`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#drain_continues), [`drain_no_escape`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Scheduler.html#drain_no_escape).
[^direct-link]: [`direct_link_preserves_well_formed`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#direct_link_preserves_well_formed), [`world_direct_link_spec`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Heap.Collections.html#world_direct_link_spec).
[^binding-cutoff]: [`signal_update_noop`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Check.html#signal_update_noop), [`cutoff`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Runs.html#cutoff).
[^direct-unlink]: [`direct_unlink_preserves_well_formed`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Collections.html#direct_unlink_preserves_well_formed).
[^bridge-cutoff]: [`bridge_ce_projected_cutoff_and_unready_guard`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Concurrency.html#bridge_ce_projected_cutoff_and_unready_guard).
