Skip to main content

Reactive UI

Proposal

This page is a design sketch. Nothing on it is implemented: there's no reactive state, no markup syntax and no html package yet. The markup syntax below is a placeholder and will change. Effect types are written as in the effects design.

This section outlines a React-like framework for Bolt. This page writes down how it could work: components whose state and async work are algebraic effects, compiled the way Svelte 5 compiles its components.

Problems with a direct port of React​

  • State that is set while drawing. Assigning to state while a component renders reruns it, forever. State should change from events, like a click, or from effects, not while drawing.
  • Several booleans for one state. is_loading, is_error and is_ok can all be true at once. Bolt has enums and match, so a request should be one value, like Loading | Failed(e) | Done(data), which the compiler checks for every case.
  • Which state is which. If a component reruns on each change, every piece of state has to find the same cell again. React ties state to the order of hook calls, which is why hooks can't be called in if or in loops.
  • What a component is. A plain fn with hidden state isn't an ordinary function anymore. The compiler should know where state lives, and reject state in functions that aren't components.

Components as effectful functions​

A component is a function whose type says it uses the Reactive effect, and maybe Async, the effect of code that waits, like fetch. That one has a page of its own.

effect Reactive {
fn state[T](key: Key, init: T) -> Signal[T]; // the key comes from the compiler
fn read[T](s: Signal[T]) -> T;
}

fn app() -> Html does Reactive + Async {
let mut user = None; // state, see below: let user = state(<key>, None)
match user { ... } // match read(user) { ... }
}

This gives:

  • Components in the types. Using state outside a component is a type error, unless something handles Reactive. That's problem 4.
  • Runtimes that can be swapped. The same component runs under a DOM handler in the browser, a server handler that renders HTML once without tracking anything, a hydration handler, or a test handler.
  • Dependency tracking. Every read is an operation the handler sees, so it can record what a computation depends on. Solid and Svelte 5 do this with a global "current listener" variable, which is an untyped effect handler in all but name.
  • Async without rerunning. A call that waits, like fetch, suspends the component: the handler shows a fallback, and resumes the component when the data is there. React's Suspense throws a promise and reruns the component instead, because JavaScript can't resume a function halfway.

Inferring state​

There's no keyword for state. A component's body runs once, and only the bindings in its markup rerun, so the compiler can tell from one function body which variables are state:

fn counter() -> Html does Reactive {
let mut count = 0; // written later, by on_click: state
let doubled = count * 2; // reads state: derived
let mut total = 0; // only used while drawing: a plain variable
for x in [1, 2, 3] { total += x; }
button(on_click: || { count += 1; }) {[count, " × 2 = ", doubled]}
}
  • State is a let mut that a closure writes after drawing is done, like an event handler. Closures already change the mut variables they capture, so this is a check within one function.
  • Derived is a let whose value reads state. It's recomputed when the state changes; otherwise doubled would be computed once and go stale. Only an expression without effects can be derived, because running a print again would change what the program does. The effects in its type tell the compiler which expressions those are.
  • Plain is everything else, like total. It's an ordinary variable and costs nothing.

Bolt already infers types, and inferring Reactive is the same kind of work. It also has no split between component files and other files, like .svelte and .js.

Inference has limits:

  • Function boundaries. Passing count to a function passes its value, not its cell, so moving code into a helper would quietly lose reactivity. This is why Svelte 5 dropped the inference of Svelte 4. A function that reads or changes state says so, with a Signal[T] parameter or result. The compiler could pass the cell itself when the parameter's type is Signal[T], but not when that type is inferred, so this stays explicit.
  • Changes inside data. items.push(x) or user.name = "Sam" changes an object, not a variable. Objects are garbage-collected and can be shared, so the compiler can't follow every path to them. To start with, only assigning a whole new value counts, as in items = items.push(x). Collections that track their own changes can come later; Svelte 5 uses proxies for this. The types also tell which calls change their argument: see Mutability and effects.
  • Predictability. Small changes change the meaning: removing the last event handler that writes count makes it a plain variable. The language server shows what the compiler inferred, with an inlay hint or a highlight on state and derived variables, like rust-analyzer shows inferred types.

What effects don't solve​

  1. Keys for state. A handler only sees state calls one after another, so effects alone bring back the rules of hooks. The compiler passes a key with each call: its place in the source, and the key of the item in a loop. Then state in match, if and loops is fine.
  2. Writes from event handlers. An on_click runs after drawing is done, outside of the handler, so it can't perform Reactive. state returns a first-class Signal[T], and writing is a plain method that schedules an update: user = x in a handler becomes user.set(x). Only creating and reading state are effects.
  3. Fine-grained updates. If reads are tracked per component, every change reruns the whole component, which is React with better types. To update only the text of one h1, the compiler splits the markup into one small computation per binding, each run under a tracking handler. Effects don't split code; this is the compile-time part of Svelte and Solid.
  4. Rerunning by resuming. Resuming a saved continuation more than once to redraw clashes with mutation and with the DOM, and many runtimes resume a continuation only once (OCaml 5 does). Rerunning means calling the function again. The types can tell which continuations are safe to resume more than once: see Mutability and effects.
  5. The cost of compiling effects. General effects need stack switching or a CPS transform, which is slow when compiled to JavaScript. But state and read resume right away, and such operations compile to a hidden argument, almost for free, as in Koka. Only Async suspends (more on that); in wasm, JSPI and stack switching can help there.
  6. Effect polymorphism. list.map(|x| item(x: x)) only type checks if map passes on the effects of its callback. Effect rows are the same idea as the rows of extensible records ({ name: str, .. }), so the type checker may be able to reuse that.

Mutability and effects​

Bolt's mutability types and effects cover different things. imm and mut are about data: which values can change. Effects are about computations: what a call does besides giving a value, through a handler. Together they leave a component no hidden way to change or depend on anything.

Drawing changes only what the effects reach. A named function captures nothing, so it's an imm fn, and an imm value never changes, nor does anything it holds. So a component whose props are imm changes nothing that existed before it ran, except through its effects: an operation like state is a call of the handler, and only the handler's state changes. A component can still make mut values of its own and change them, but no one else can see them. The Lean proof has this as imm_fn_changes_only_through_handler: calling an imm function with imm arguments and a handler changes only what the handler can reach.

Props that are callbacks, like on_login in the example below, change the parent's state, so they're mut fns, and what they reach can change too. Calling one while drawing is the first problem on this page; event handlers call them after drawing is done. The compiler could warn about a call of a mut fn prop while drawing.

Tracking is complete. The tracking handler sees only the reads that go through read. A mut value that a component reaches some other way could change without the handler knowing, and the page would show a stale value, which is the bug of Svelte 3 and 4. With imm props, anything that changes while drawing can only be reached through a Signal, so every read that matters is tracked. That leaves Signal[T] where T is mut: a push on the value inside isn't a write to the signal. Either T must be imm, so that a change replaces the whole value, as in items.set(items.get().push(x)), which can share most of the old one; or a call that changes it counts as a write, as below.

The types tell which calls change their argument (#200). A function can only change a parameter whose type is mut; a parameter written [T] or Vec[T] can be either, so the function can't change it. So fn push[T](v: mut Vec[T], x: T) changes v, and fn len[T](v: Vec[T]) doesn't, and the compiler can read that from the signature: passing state to a mut parameter counts as a write, without a list of methods or a Mut effect. A mut parameter that's never changed causes an update that wasn't needed, never a missed one.

Changing data isn't an effect. Koka tracks writes to the heap as an effect. In Bolt, imm is a property of a value, which can be stored, shared, and sent to another thread; an effect is a property of a call that runs. Changing a mut array a function made itself can't be seen from outside, so making it an effect would only add noise to signatures.

Continuations have a mutability too. A handler that captures the rest of a computation captures its local variables, like a closure. So a continuation is mut when the code it resumes holds a let mut variable or a mut value, by the same rule as a closure, and imm otherwise. An imm continuation can be resumed any number of times, which is problem 4 above; a mut one should be resumed at most once.

Polymorphism works the same way. A function that passes on the effects of its callback, like map, is like one that's generic over its callback's mutability: both are hidden parameters of its type, inferred from the body. Effect rows, the rows of extensible records, and the "at most" constraints of mutability may share one solver.

Compared with Svelte​

  • Svelte 3 and 4 compile everything: assignments to the top-level lets of a component are instrumented, and each DOM node gets update code. Reactivity stopped at function boundaries, which is why Svelte 5 dropped it.
  • Svelte 5 has runes: $state, $derived and $effect are signals at runtime, with dependency tracking. The compiler turns reads into $.get(x), and splits the template into one reaction per binding.
Svelte 5Bolt with effects
let count = $state(0)let mut count = 0, inferred to be state
let doubled = $derived(count * 2)let doubled = count * 2, inferred to be derived
$state(init) at runtimethe state(key, init) operation
a read, $.get(count)the read(s) operation, tracked by the handler
the global "active reaction"the handler in scope, which the types track
the template split per DOM nodethe same, each part under a tracking handler
{#await}, and Suspense in Reacta call with Async, like fetch, resumed once
server rendering as a compile modeanother handler

So the design is a Svelte 5–style compiler on an effect-based runtime. Effects give the types, the tracking, async, and handlers that can be swapped. The compiler infers what is state, gives the keys of state, and splits markup into small updates.

Using the rest of Bolt​

  • Props are keyword arguments. <Button label="Save" primary /> is button(label: "Save", primary: true), and parameter defaults are default props.
  • Children are a trailing block. A block after a call is its last argument, and the () can be left out, so children are a list literal: div(cls: "card") {[ h1 {["Hi"]}, p {["Welcome."]} ]}. With if and for in list literals, the list reads like markup. See #458 and #457.
  • Extensible records pass props on. props: { class: str, .. } is React's ...rest, but type-checked.
  • A class for interpolation. Like Show for print, a ToHtml class lets any type appear in markup, with text escaped by default.

An example​

import "html" (Html, h1, button)

fn app() -> Html does Reactive {
let mut user = None;
match user {
None => login_form(on_login: |u| { user = Some(u); }),
Some((username: username, ..)) => h1 {["Welcome back, ", username, "!"]},
}
}

fn login_form(on_login: fn(User) -> ()) -> Html does Reactive {
let mut failed = false;
// fetch waits, so the closure is inferred to be fn() -> () does Async.
// That's what on_click accepts: the page runs it as a task of its own.
let submit = || match fetch("/api/login") {
Ok(data) => on_login((username: data.username)),
Err(_) => { failed = true; },
};
if failed {
h1 {["Something went wrong."]}
} else {
button(on_click: submit) {["Log in"]}
}
}

h1 {[..]} is a call and not a struct literal because functions start with a lowercase letter and types with an uppercase one (#460).

Fetching while drawing​

fetch in submit runs in an event handler. It performs Async, waits, and resumes once with a Result. A component that fetches while drawing wants to show each state instead: loading, failed and done.

Resuming the continuation of the call once with Loading and again with Done would do it, but that's resuming more than once, which is problem 4. The code after the call usually holds a let mut, so its continuation is mut and may be resumed at most once (see Mutability and effects).

Redrawing gives the same result with one resume each time. A loader keeps the result in state, keyed like any other state (problem 1):

  1. On the first draw the state is Loading. The loader starts the request as a task and returns Loading right away.
  2. When the task is done, it writes Done(data) or Failed(e) to the state, like a write from an event handler. That schedules a redraw.
  3. On the redraw the state already holds the result, and the loader returns it.

Unlike a second resume, a redraw runs the whole component again, not only the code after the call. Drawing must be safe to run again anyway.

So there are two kinds of calls: fetch with Async in handlers, which returns a Result once, and a loader with Reactive while drawing, which returns a Remote. They return different types, so they get different names; load is a placeholder. An Async call while drawing still suspends the component, as in Components as effectful functions, for when a fallback from the handler is enough.

Example: a loader​

load needs one more Reactive operation, task, which starts a task from a component. Everything else is inferred state:

import "http" (fetch, HttpError, Decode)
import "html" (Html, h1, p)

enum Remote[T, E] { Loading, Failed(E), Done(T) }

/// Starts `f` as a task the first time this call is drawn. When `key`
/// changes, it cancels the old task and starts a new one. The task is
/// also cancelled when the component leaves the page.
#[builtin]
fn task[K: Eq](key: K, f: fn() -> () does Async) -> () does Reactive;

pub fn load[T: Decode](url: String) -> Remote[T, HttpError] does Reactive {
// Written by the task after drawing is done, so it's inferred to be
// state. The write schedules a redraw.
let mut remote = Loading;
task(key: url) {
remote = Loading;
remote = match fetch(url).and_then(|res| res.json[T]()) {
Ok(value) => Done(value),
Err(e) => Failed(e),
};
};
// Reading state: the handler records that the caller depends on it.
remote
}

fn profile() -> Html does Reactive {
match load[User]("/foobar") {
Loading => p {["Loading…"]},
Failed(e) => p {["Error: ", e.message]},
Done(user) => h1 {["Hi ", user.username]},
}
}
  1. First draw. remote is state holding Loading. task starts the request and returns at once, so load returns Loading.
  2. The request is done. The task writes Done(..) or Failed(..); it runs outside drawing, so that's remote.set(..), which schedules a redraw of profile.
  3. Redraw. remote keeps what was stored, task sees the same url and does nothing, and load returns Done(user).
  4. The URL changes. task cancels the old request and starts a new one, so a late answer for the old URL can't overwrite the new one.

Open points:

  • Keys across functions. remote and task live in load, so their keys must include where load was called, like a path of call sites. Otherwise two calls to load in one component share their state.
  • task(key: url) { .. } needs trailing closures (#462): f has a function type, so the block becomes a closure and isn't run while drawing. Without them it's task(key: url, || { .. }).
  • let mut remote = Loading sets the state once, not on every draw. That's what inferred state means, but it's easy to misread here.
  • Errors. Decoding probably has its own error, so a real load has a sum of errors or an error parameter with From.
  • task is a first version of effects with cleanup, below.

Still to design​

  • Children beyond the trailing block: which parameter it fills, and more than one slot, like a header and a body (#458).
  • Lists and their keys.
  • Effects with cleanup, like timers and subscriptions, and what happens when a component leaves the page.
  • Context, for values like the user that is logged in.
  • Mounting, and what this compiles to: JavaScript, or wasm.
  • Typed elements and attributes. With elements as functions, img(scr: ..) is already an error, an unknown keyword argument. What's left is the many attributes every element shares, and data-* and aria-*.
  • Rendering on the server, and hydration.

A first step​

The Reactive effect with only operations that resume right away, the inference of state, and the keys from the compiler. That gives state that behaves well and components in the types, without the hard parts of compiling effects. Derived values, splitting markup and Async come later.