Skip to content

Refs and lifecycleNew in 7.2

Reach the real DOM, run code on mount and cleanup, render elsewhere, and recover from errors.

docs/learn/lifecycle.md
moduleXote.Viewboundarysrc/View.resientryxote · xote/viewversion7.2.0
Raw MarkdownAPI reference

Most components only need signals and JSX. This page covers the extra tools for the rest: reaching the real DOM element, running code when a component appears or goes away, rendering somewhere else on the page, and containing errors.

Run code when a component mounts

A component's body runs before its elements are on the page, so you can't focus or measure them there yet. View.onMount runs a function once the component is in the document. View.onCleanup runs one when it's removed.

1@xote.component
2let make = () => {
3 let now = Signal.make(Date.now())
4 View.onMount(() => {
5 let id = setInterval(() => Signal.set(now, Date.now()), 1000)
6 View.onCleanup(() => clearInterval(id))
7 })
8 <time> {Date.fromTime(Signal.get(now))->Date.toLocaleTimeString} </time>
9}

Whatever you set up in onMount should be undone in onCleanup: timers, listeners, subscriptions. Effects started inside it are cleaned up with the component automatically.

onMount never runs during server rendering. In the browser it runs after hydration, which makes it the safe place for code that needs window or document.

Reach a DOM element with a ref

Create a ref with View.Ref.make and pass it to an element's ref prop. The element is filled in before any onMount runs.

1@send external focus: Dom.element => unit = "focus"
2
3@xote.component
4let make = () => {
5 let field = View.Ref.make()
6 View.onMount(() => View.Ref.peek(field)->Option.forEach(focus))
7 <input ref=field type_="search" placeholder="Search" />
8}

View.Ref.peek reads the element once. A ref is backed by a signal, so View.Ref.get inside an effect reruns it when the element arrives or goes away. View.Ref.fromCallback makes a ref that also calls your function with each element.

Render somewhere else with a portal

View.Portal renders its children into another element, document.body by default. Use it for modals, tooltips and menus that need to escape a parent's overflow: hidden or stacking order.

1module Modal = {
2 @xote.component
3 let make = (~children: View.node) =>
4 <View.Portal>
5 <div class="modal-backdrop" onClick={_ => Signal.set(isOpen, false)}>
6 <div class="modal"> {children} </div>
7 </div>
8 </View.Portal>
9}

Pass target to render into a specific element. When the portal is removed, everything it rendered goes with it. On the server a portal renders nothing.

DOM events from inside a portal bubble through the element it renders into, not through the component that contains it.

Contain errors with a boundary

View.ErrorBoundary stops one failing part of the page from taking down the rest. If anything inside it throws while rendering or updating, it shows fallback instead.

1<View.ErrorBoundary
2 fallback={(_error, reset) =>
3 <p>
4 {"This panel failed to load. "}
5 <button onClick={_ => reset()}> {"Retry"} </button>
6 </p>}
7 onError={error => Console.error(error)}>
8 <Dashboard />
9</View.ErrorBoundary>

reset renders the contents again from scratch. Boundaries nest: the nearest one catches.

A boundary catches errors from component bodies, reactive text and attributes, and effects started while rendering. It does not catch errors in event handlers, timers or promise callbacks, since those run later; handle them where they happen.

With server rendering, a part that fails renders its fallback into the HTML, and the browser renders everything inside that boundary again instead of reusing the server's markup. Wrap the parts of a page that can fail, not the whole app.

Common mistakes

  • Touching the DOM in the component body. Elements aren't on the page yet. Use onMount.
  • Forgetting cleanup. A timer started in onMount keeps running after the component is gone unless onCleanup stops it.
  • Expecting a boundary to catch a click handler's error. Catch it in the handler.

Summary

Lifecycle tools let a component touch the real DOM and the outside world at the right time: View.onMount runs code once the component's DOM is in the document, View.onCleanup runs code when the component is removed, View.Ref hands over an element, View.Portal renders children into another element, and View.ErrorBoundary replaces a failing subtree with a fallback. The rule that matters most: anything that needs a laid-out, focusable element MUST run in onMount (or an effect that reads a ref with View.Ref.get), never in the component body.

Availability

ItemModule / entryStable sinceChanged in 7.2.0PPX required
View.onMount, View.onCleanupxote · xote/view7.2.0 (new)—no
View.Ref (make, fromCallback, get, peek), ref propxote · xote/view7.2.0 (new)—no
View.Portalxote · xote/view7.2.0 (new)—no
View.ErrorBoundaryxote · xote/view7.2.0 (new)—no
Effect returning a cleanup (Some(() => …))xote · xote/effect7.1.0—no

Before 7.2.0, the only lifecycle tool is an effect created in the component body with a returned cleanup; there is no mount hook, no ref and no error boundary.

Rules

View.onMount

  1. Call View.onMount(callback) in a component body. callback runs once, after the render that created the component has inserted all of its DOM into the document, refs included.
  2. Order: within one render, a parent's onMount runs before its children's (all of them run only after the whole tree is inserted).
  3. callback runs untracked (reads subscribe nothing), under the component's context and error boundary.
  4. View.onCleanup and Effect.run called inside callback are owned by the component and released when it is removed.
  5. A component removed before its DOM was inserted (for example a subtree an error boundary replaced) never runs its onMount.
  6. onMount never runs during server rendering. After hydration it runs once the page is interactive.
  7. A component function called directly (View.mount(app(), container)) schedules its onMount before anything renders; it then waits for the next View.mount or hydration.
  8. A failing onMount goes to the nearest View.ErrorBoundary. Without a boundary, the remaining onMount callbacks of the batch still run and the exception is then raised from View.mount.

View.onCleanup

  1. Call it in a component body or inside that component's onMount. callback runs once, untracked, when the component is removed.
  2. Registered in the body, it runs even if the component never mounted (for example its subtree was replaced by an error boundary), because the body that allocated resources did run.
  3. Outside any component, there is nothing to remove and the callback never runs.
  4. Order on removal: a parent's cleanups run before its children's.
  5. For an effect's own teardown, return the cleanup from the effect (Some(() => …)) instead; it also runs before every re-run of the effect.

View.Ref

  1. View.Ref.make() creates a ref; pass it to an intrinsic element as ref (<input ref=field />, or ~ref on View.element). Not a prop of user components unless they declare one.
  2. The element is handed over once it is in the document, before any onMount runs; the ref reads None again when the element is removed.
  3. View.Ref.peek(ref) reads the element untracked. View.Ref.get(ref) is a tracked read: an effect or computed calling it re-runs when the element arrives or goes.
  4. View.Ref.fromCallback(cb) creates a ref that also calls cb (untracked) with each element handed to it. A failing callback does not hold back the onMount callbacks.
  5. A ref follows one element; given to several elements it holds whichever was inserted last.
  6. On the server no DOM exists and a ref stays None; hydration hands the ref the server-rendered element.

View.Portal

  1. <View.Portal target=? > children </View.Portal> renders children into target (default document.body) and nothing where the portal stands.
  2. Children render under the portal's context and error boundary, stay reactive, and are inserted into the target after the rest of the render, before refs and onMount callbacks run: a component's onMount can read refs of elements inside its portal. Inside a View.Suspense that is still waiting, they are inserted once the suspense shows its children.
  3. Portal content sits between two comment anchors in the target. Removing the portal removes everything between them (including nodes children added later, such as new keyed rows) and releases everything they set up.
  4. DOM events bubble through the target's DOM ancestors, not through the portal's position in the component tree.
  5. On the server a portal renders nothing; its children render into the target on the client after hydration.

View.ErrorBoundary

  1. Props: fallback: (exn, unit => unit) => node (required), onError?: exn => unit, children?: node.
  2. Caught: failures while the subtree renders and updates — a component body, a reactive region re-rendering (View.tracked, Show, For, if/switch regions), a reactive text or attribute, an Effect.run set up in a component body (first run, later runs and its cleanup), and an onMount callback.
  3. Not caught: event handlers, timers, promise callbacks (they run outside any render), and a Computed made with ~equals (its failure goes to the code that wrote the signal). Handle these where they happen.
  4. A failure from a region outside the boundary is never claimed, even when a write inside the boundary caused that region to update.
  5. On a caught failure, the whole subtree is released (its cleanups run) and fallback(error, reset) renders in its place. reset() renders the subtree again from scratch (new component instances, new local state).
  6. onError is called for every failure the boundary catches; when several fail in one render, the fallback shows the first.
  7. Boundaries nest: the nearest one catches. A failure inside fallback goes to the boundary above.
  8. Signals read while building fallback do not subscribe the boundary (the fallback is not rebuilt when they change); reactive leaves inside the fallback's JSX still update.
  9. The subtree keeps the context provided above the boundary.
  10. The boundary renders a <div style="display: contents"> around its subtree (affects CSS child selectors such as >).
  11. To route an async failure from a resource to a boundary, throw it where the state is read: | Failed(exn) => throw(exn) in a reactive leaf or region.

API

NameSignatureBehaviour
View.onMount(unit => unit) => unitRun once after the component's DOM is inserted.
View.onCleanup(unit => unit) => unitRun once when the component is removed.
View.Ref.makeunit => View.Ref.tA ref; None until its element is in the document.
View.Ref.fromCallback(Dom.element => unit) => View.Ref.tA ref that also calls back with each element.
View.Ref.getView.Ref.t => option<Dom.element>Tracked read of the element.
View.Ref.peekView.Ref.t => option<Dom.element>Untracked read of the element.
View.Portalprops {target?: Dom.element, children?: node}Render children into another element.
View.ErrorBoundaryprops {fallback: (exn, unit => unit) => node, onError?: exn => unit, children?: node}Contain failures of a subtree.
Effect.run(unit => option<unit => unit>, ~name: string=?) => unitEffect; the returned cleanup runs before re-runs and on disposal.

Patterns

Focus an element after mount. Use when: autofocus, measuring, third-party DOM libraries.

1@send external focus: Dom.element => unit = "focus"
2
3module AutoFocus = {
4 @xote.component
5 let make = () => {
6 let field = View.Ref.make()
7 View.onMount(() => View.Ref.peek(field)->Option.forEach(focus))
8 <input ref=field type_="search" />
9 }
10}

Start and stop a timer. Use when: intervals, subscriptions, listeners.

1@val external setInterval: (unit => unit, int) => int = "setInterval"
2@val external clearInterval: int => unit = "clearInterval"
3
4module Clock = {
5 @xote.component
6 let make = () => {
7 let now = Signal.make(Date.now())
8 View.onMount(() => {
9 let id = setInterval(() => Signal.set(now, Date.now()), 1000)
10 View.onCleanup(() => clearInterval(id))
11 })
12 <time> {Date.fromTime(Signal.get(now))->Date.toLocaleTimeString} </time>
13 }
14}

React to the element arriving. Use when: the element can appear later (inside a conditional) or be replaced.

1@get external offsetWidth: Dom.element => int = "offsetWidth"
2
3module Measure = {
4 @xote.component
5 let make = () => {
6 let box = View.Ref.make()
7 let width = Signal.make(0)
8 Effect.run(() => {
9 switch View.Ref.get(box) {
10 | Some(el) => Signal.set(width, offsetWidth(el))
11 | None => ()
12 }
13 None
14 })
15 <div ref=box> {Signal.get(width)} </div>
16 }
17}

Modal through a portal. Use when: content must escape overflow: hidden or stacking contexts.

1module Modal = {
2 @xote.component
3 let make = (~onClose: unit => unit, ~children: View.node) =>
4 <View.Portal>
5 <div class="backdrop" onClick={_ => onClose()}>
6 <div class="modal"> {children} </div>
7 </div>
8 </View.Portal>
9}
10
11let isOpen = Signal.make(false)
12
13module App = {
14 @xote.component
15 let make = () =>
16 <div>
17 <button onClick={_ => Signal.set(isOpen, true)}> {"Open"} </button>
18 {Signal.get(isOpen) ? <Modal onClose={() => Signal.set(isOpen, false)}> <p> {"Hi"} </p> </Modal> : View.null()}
19 </div>
20}

Error boundary with retry and typed errors. Use when: a part of the page can fail independently.

1exception LoadFailed(string)
2
3module Guarded = {
4 @xote.component
5 let make = () =>
6 <View.ErrorBoundary
7 fallback={(error, reset) =>
8 <div role="alert">
9 <p>
10 {switch error {
11 | LoadFailed(message) => message
12 | _ => "Something went wrong."
13 }}
14 </p>
15 <button onClick={_ => reset()}> {"Retry"} </button>
16 </div>}
17 onError={error => Console.error(error)}>
18 <Dashboard />
19 </View.ErrorBoundary>
20}

Anti-patterns

DOM access in the component body.

1@xote.component
2let make = () => {
3 let field = View.Ref.make()
4 View.Ref.peek(field)->Option.forEach(focus) // always None here
5 <input ref=field />
6}

Symptom: nothing happens (the ref is None while the body runs). Fix: move the call into View.onMount(() => …). Why: the body runs before the element exists in the document.

Timer without cleanup.

1View.onMount(() => {
2 let _ = setInterval(() => Signal.update(ticks, n => n + 1), 1000)
3})

Symptom: after the component is removed the interval keeps running and keeps writing signals (leak; possible writes to disposed state). Fix: View.onCleanup(() => clearInterval(id)) inside the same onMount.

Expecting a boundary to catch an event handler.

1<button onClick={_ => throw(Failure("boom"))}> {"Go"} </button>

Symptom: the boundary fallback never shows; the error surfaces as an uncaught exception. Fix: catch in the handler (try … catch) and set an error signal that the UI renders, or move the failing work into a resource and throw its Failed(exn) from a reactive leaf.

Wrapping the whole app in one boundary with SSR.

Symptom: hydration re-renders everything inside the boundary on the client instead of adopting the server DOM (slower first interaction, lost server DOM reuse). Fix: wrap only the parts that can fail.

Expecting portal events to bubble to the component's parent element.

Symptom: a click handler on an ancestor element of the <View.Portal> does not fire for clicks inside the portal content. Fix: attach handlers inside the portal content, or on the target element.

Relying on > CSS selectors across a boundary.

Symptom: .list > .item stops matching when items are inside an error boundary (wrapped in <div style="display: contents">). Fix: use descendant selectors or put the boundary inside each item.

Edge cases

  • onMount in a keyed list row runs per row, including rows added later.
  • A component shown on a later update (inside a branch that becomes true) runs its onMount when it is inserted, and its cleanups when it is removed.
  • An effect created in the body runs immediately, before the DOM is inserted; use View.Ref.get inside it to re-run when the element arrives, or use onMount.
  • reset() re-runs component bodies inside the boundary: local signals are created again; module-level signals are untouched.
  • An error boundary inside each keyed row isolates failures per row.
  • onError is for logging; it cannot prevent the fallback.

SSR and hydration

  • Server: no onMount, refs stay None, portals render nothing, a failing subtree renders its boundary's fallback into the HTML.
  • Hydration: refs receive the server elements, onMount runs once interactive, portal children render into their target, and every subtree inside an ErrorBoundary is rendered again on the client rather than adopted.
  • Code that touches window/document MUST run in onMount, in an effect guarded by SSRContext.isClient, or in event handlers.

Verify

  • jsdom: mount a component whose onMount pushes to a log and reads a ref; assert the log has one entry and the ref was Some with isConnected == true.
  • Removal: toggle the condition that shows the component and assert cleanup callbacks ran once.
  • Boundary: render a child that throws in its body; assert the fallback's markup is present and the child's markup is absent; call reset after fixing the cause and assert the child renders.
  • Portal: assert content is a descendant of document.body (or the target) and not of the component's container; remove the portal and assert the content is gone.
  • /docs/learn/components — component bodies run once; ownership.
  • /docs/learn/effects — effects and cleanups (available in 7.1.0 stable).
  • /docs/learn/async-data — resources and View.Suspense; throwing Failed into a boundary.
  • /docs/advanced/ssr — server rendering and hydration.
  • /docs/api/view — full View reference.

API reference

This page lists the supported API for the View module.

Node is intentionally not expanded here. It currently exists as a compatibility alias, but new code and docs should use View.

View

View is the UI node API used by JSX components and lower-level rendering helpers.

View types

1type attrValue =
2 | Static(string)
3 | SignalValue(Signal.t<string>)
4 | Compute(unit => string)
5
6type node

View.node is the renderable value returned by components. View.attrValue is the supported attribute source type.

View.attr

1let attr: (string, string) => (string, View.attrValue)

Create a static attribute entry.

View.signalAttr

1let signalAttr: (string, Signal.t<string>) => (string, View.attrValue)

Create a reactive attribute from a string signal.

View.computedAttr

1let computedAttr: (string, unit => string) => (string, View.attrValue)

Create a reactive attribute from a compute function.

View.Attr

1View.Attr.string: (string, string) => (string, View.attrValue)
2View.Attr.signal: (string, Signal.t<string>) => (string, View.attrValue)
3View.Attr.compute: (string, unit => string) => (string, View.attrValue)

Namespaced aliases for View.attr, View.signalAttr, and View.computedAttr.

View.text

1let text: string => View.node

Create a static text node.

View.int

1let int: int => View.node

Create a static integer text node.

View.float

1let float: float => View.node

Create a static float text node.

View.bool

1let bool: bool => View.node

Create a static boolean text node.

View.signalText

1let signalText: (unit => string) => View.node

Create a reactive text node from a compute function.

View.signalInt

1let signalInt: (unit => int) => View.node

Create a reactive integer text node from a compute function.

View.signalFloat

1let signalFloat: (unit => float) => View.node

Create a reactive float text node from a compute function.

View.fragment

1let fragment: array<View.node> => View.node

Group several nodes without adding a wrapper element.

View.signalFragment

1let signalFragment: Signal.t<array<View.node>> => View.node

Render an array of nodes from a signal and replace the fragment when it changes.

View.tracked

1let tracked: (unit => View.node) => View.node

Create an auto-tracked reactive block. Every signal read while the body runs subscribes the block, and the body re-evaluates when any dependency changes. Dependencies are re-discovered on each run, so conditional reads work. The block's children are replaced wholesale (no diffing) on update — keep tracked blocks small and use View.For or View.eachWithKey for lists.

View.each

1let each: (Signal.t<array<'a>>, 'a => View.node) => View.node

Render each item from a reactive array. Updates re-render the list contents.

View.list

1let list: (Signal.t<array<'a>>, 'a => View.node) => View.node

Alias for View.each.

View.eachWithKey

1let eachWithKey: (Signal.t<array<'a>>, 'a => string, 'a => View.node) => View.node

Render a reactive array with keyed DOM reconciliation.

View.keyedList

1let keyedList: (Signal.t<array<'a>>, 'a => string, 'a => View.node) => View.node

Alias for View.eachWithKey.

View.For

1module For: {
2 type props<'item> = {
3 each: MaybeSignal.t<array<'item>>,
4 by?: 'item => string,
5 render: 'item => View.node,
6 }
7
8 let make: props<'item> => View.node
9}

JSX list primitive. Pass by to enable keyed reconciliation.

View.KeyedFor

1module KeyedFor: {
2 type props<'item> = {
3 each: MaybeSignal.t<array<'item>>,
4 by: 'item => string,
5 render: 'item => View.node,
6 }
7
8 let make: props<'item> => View.node
9}

JSX list primitive that always requires a key function.

View.Show

1module Show: {
2 type props = {
3 when_: MaybeSignal.t<bool>,
4 children?: View.node,
5 fallback?: View.node,
6 }
7
8 let make: props => View.node
9}

JSX conditional primitive for boolean branches.

View.Maybe

1module Maybe: {
2 type props<'value> = {
3 value: MaybeSignal.t<option<'value>>,
4 render: 'value => View.node,
5 fallback?: View.node,
6 }
7
8 let make: props<'value> => View.node
9}

JSX conditional primitive for option values.

View.Value

1module Value: {
2 type props<'value> = {
3 value: MaybeSignal.t<'value>,
4 render: 'value => View.node,
5 }
6
7 let make: props<'value> => View.node
8}

JSX primitive that re-renders a node from one static or reactive value.

View.Suspense

New in 7.2
1module Suspense: {
2 type props = {
3 fallback?: View.node,
4 children?: View.node,
5 }
6
7 let make: props => View.node
8}

Shows fallback until every Resource created below it has loaded once. The children render hidden meanwhile, and their refs and onMount callbacks wait until they are shown. See Resources.

View.Ref

New in 7.2
1module Ref: {
2 type t = View.elementRef
3
4 let make: unit => t
5 let fromCallback: (Dom.element => unit) => t
6 let get: t => option<Dom.element>
7 let peek: t => option<Dom.element>
8}

A handle on the DOM element a tag renders to. Pass it as ref (<input ref=field />, or ~ref on View.element). The element is handed over once it is in the document, before any onMount runs, and the ref reads None again once the element is removed. get is a tracked read; fromCallback also calls a function with each element.

View.onMount

New in 7.2
1let onMount: (unit => unit) => unit

Runs a callback once the calling component's DOM is in the document. Call it in a component body. It runs untracked, under the component's context and error boundary, and never during server rendering.

View.onCleanup

New in 7.2
1let onCleanup: (unit => unit) => unit

Runs a callback when the calling component is removed. Call it in a component body or inside its onMount.

View.Portal

New in 7.2
1module Portal: {
2 type props = {
3 target?: Dom.element,
4 children?: View.node,
5 }
6
7 let make: props => View.node
8}

Renders its children into target (document.body if omitted), and nothing where it stands; they are in the target before any onMount of the render runs. The children keep the portal's context and error boundary, and are removed with it.

View.ErrorBoundary

New in 7.2
1module ErrorBoundary: {
2 type props = {
3 fallback: (exn, unit => unit) => View.node,
4 onError?: exn => unit,
5 children?: View.node,
6 }
7
8 let make: props => View.node
9}

Catches what its subtree throws while rendering or updating and renders fallback instead. fallback receives the failure and a reset function that renders the subtree again; onError is called with every failure caught.

View.element

1let element: (
2 string,
3 ~attrs: array<(string, View.attrValue)>=?,
4 ~events: array<(string, Dom.event => unit)>=?,
5 ~children: array<View.node>=?,
6 ~ref: View.elementRef=?,
7 unit,
8) => View.node

Create an element node for any tag.

View.null

1let null: unit => View.node

Create an empty placeholder text node.

View.empty

1let empty: unit => View.node

Alias for View.null.

View.mount

1let mount: (View.node, Dom.element) => unit

Render a node into a DOM element.

View.mountById

1let mountById: (View.node, string) => unit

Look up a DOM element by id and mount into it.

View.Text

1<View.Text>{value}</View.Text>
2<View.Text value={value} />

JSX text primitive. value or children may be a raw string, Signal.t<string>, MaybeSignal.t<string>, or unit => string.

View.Int

1<View.Int>{value}</View.Int>
2<View.Int value={value} />

JSX integer text primitive. value or children may be a raw int, Signal.t<int>, MaybeSignal.t<int>, or unit => int.

View.Float

1<View.Float>{value}</View.Float>
2<View.Float value={value} />

JSX float text primitive. value or children may be a raw float, Signal.t<float>, MaybeSignal.t<float>, or unit => float.

View.Bool

1<View.Bool>{value}</View.Bool>
2<View.Bool value={value} />

JSX boolean text primitive. value or children may be a raw bool, Signal.t<bool>, MaybeSignal.t<bool>, or unit => bool.

Example

1open Xote
2
3let count = Signal.make(0)
4
5let app = () => {
6 <div>
7 <View.Text> "Count: " </View.Text>
8 <View.Int> {count} </View.Int>
9 <button onClick={_ => Signal.update(count, n => n + 1)}>
10 <View.Text> "Increment" </View.Text>
11 </button>
12 </div>
13}
14
15View.mountById(app(), "app")

See Also