Effect UI, and Why This Site Runs on It
- Overview
Effect UI is a frontend framework from the Effect-TS organization: a component is a few Schemas and three pure functions, and every side effect is data the runtime runs for you. A tour of how it works, with a live component, how it renders and tests, and what moving this site onto it was like.
- Technologies
- EffectEffect UIFrontendTypeScriptTestingServer Rendering

What Effect UI Is
Effect UI (@effect/ui) is a frontend framework from the Effect-TS organization. A component is a handful of Schemas, for its props, its Model and its messages, and three pure functions: init, update and view. Anything that touches the outside world, such as an HTTP call, a timer or a DOM node, is described as data: a Command, a Subscription, a Query or a Mount. The runtime runs those for you. An app is composed from Layers, the same way an Effect backend is.
If that sounds like Elm, it should. The Model, message, update and view loop is The Elm Architecture. Effect brings the rest: Schemas for every piece of state, typed errors, services and Layers for dependencies, and Streams for anything that keeps happening.
This site moved onto Effect UI from Astro and React, and is now one Effect UI app, server-rendered and hydrated in the browser. This article walks through what I learned: what a component looks like, where side effects go, how pages render on the server, how you test it, and what the move was like. The stopwatch in the next section is a real Effect UI component running on this page.
Props, Model, messages and events are Effect Schemas. The same Schemas validate an API payload on the server and the state a page hydrates from in the browser.
update takes the Model and a message and returns the next Model, plus any Commands to run. It never awaits anything, so it is just a function to test.
A component declares the work it wants done. The runtime runs it, cancels it when the Model stops asking, and feeds the results back in as messages.
Effect UI is experimental and not on npm yet. This site pins a pkg.pr.new snapshot of one commit of Effect-TS/ui, alongside Effect 4.1.
One Component, Start to Finish
Here is the stopwatch. Start it, take a lap, stop it. Its model and subscriptions panels print the Model and the Subscriptions it has asked for, live, so you can watch the state change and the timer come and go.
0:00.0
Start it, then press lap while it runs.
model
running: false tenths: 0 laps: []
subscriptions
none
Every part of it is in the file below, and each part has one job:
- The Model is a Schema. The stopwatch's whole state is three fields: whether it is running, how many tenths of a second have passed, and the laps. Nothing else is stored anywhere.
- Messages are a tagged enum. Every button press and every tick of the clock arrives as a value, such as
ClickedLap()orTicked(). - update is one case per message. Each case gets the current Model through
$and returns the next one.$.evolvechanges only the fields it names. A lap while the stopwatch is stopped returns the Model unchanged. - Subscriptions are a function of the Model. While
runningis true, the list holdstick, a Stream that emitsTickedevery 100 ms. When it goes false, the runtime closes the Stream. There is nosetIntervaland no cleanup to forget. - view is a function of the Model. This one hands the Model and four messages to a plain view helper,
StopwatchPanel. The helper draws markup and holds no state, so it can stay generic over the message type.
import { Subscription, UiSchema } from "@effect/ui";
import { Html } from "@effect/ui/html";
import { Array as Arr, Schema, Stream } from "effect";
import { StopwatchPanel } from "./StopwatchPanel.ts";
export const StopwatchModel = Schema.Struct({
running: Schema.Boolean,
tenths: Schema.Int,
laps: Schema.Array(Schema.Int),
});
export const StopwatchMessage = UiSchema.TaggedEnum({
ClickedStart: {},
ClickedStop: {},
ClickedLap: {},
ClickedReset: {},
Ticked: {},
});
const tick = Subscription.make(
"Tick",
Stream.tick("100 millis").pipe(Stream.drop(1), Stream.as(StopwatchMessage.Ticked())),
);
export const Stopwatch = Html.component({
name: "Stopwatch",
props: Schema.Struct({}),
model: StopwatchModel,
message: StopwatchMessage,
}).make({
init: () => ({ running: false, tenths: 0, laps: [] }),
update: {
ClickedStart: ($) => $.evolve({ running: true }),
ClickedStop: ($) => $.evolve({ running: false }),
ClickedLap: ($) =>
$.model.running ? $.evolve({ laps: (laps) => Arr.prepend(laps, $.model.tenths) }) : $.model,
ClickedReset: ($) => $.evolve({ running: false, tenths: 0, laps: [] }),
Ticked: ($) => ($.model.running ? $.evolve({ tenths: (tenths) => tenths + 1 }) : $.model),
},
subscriptions: ({ model }) => [model.running && tick],
view: (h, model) =>
StopwatchPanel(h, {
model,
start: StopwatchMessage.ClickedStart(),
stop: StopwatchMessage.ClickedStop(),
lap: StopwatchMessage.ClickedLap(),
reset: StopwatchMessage.ClickedReset(),
}),
});
The view is TypeScript, not JSX: h.div.class("…").children(…). Elements are typed per tag, so h.button takes button attributes and an .on("click", message) handler that can only send this component's messages. Inline .style() values for things like positions are allowed; everything static stays in classes.
Four Kinds of Side Effect, All Declared
A component never performs I/O itself. It says what it wants, and the runtime does the work, owns its lifetime and turns the outcome into a message. There are four ways to ask, and picking the right one is most of the design:
one piece of work, once
Something update asks for in response to a message: save a note, send a chat message, move focus. Its body is an Effect, and it answers with one of the component's own messages. A mode decides what happens when a second one starts while the first is running: switch, queue and others.
a stream, while the Model asks
A keyed Stream that runs for as long as subscriptions returns it: a timer while the stopwatch runs, an event stream while you are connected. Change the key and the old Stream closes before the new one starts. It never runs on the server.
data a component shows
Declared under queries by name. The runtime fetches it, caches it, keeps the result beside the Model and re-renders when it changes. The view reads it as an AsyncResult, so loading and failure are always handled. The Model holds what the user did, never a copy of fetched data.
work that needs a DOM node
Measuring an element, drawing on a canvas, hosting a chart or an editor. It is attached to the element in the view and reports back as a message. Mounts never run on the server or in tests, where the test supplies what the mount would have produced.
A Command is a class with Schemas for its arguments and its result, and a Layer for its implementation. This one, from Effect UI's guide, saves a note through a Notes service and maps both outcomes to the editor's messages. mode: "queue" runs saves in order, and invalidates tells every Query tagged with notes to refetch.
export class SaveNote extends Command.Service<SaveNote>()(
"notes/SaveNote",
{
args: { note: Note },
success: NoteEditorMessage,
mode: "queue",
invalidates: () => [NotesTag]
}
) {
static readonly layer = this.toLayer(
Effect.gen(function*() {
const notes = yield* Notes
return ({ note }) =>
notes.save(note).pipe(
Effect.match({
onSuccess: (note) => NoteEditorMessage.SucceededSaveNote({ note }),
onFailure: (error) =>
NoteEditorMessage.FailedSaveNote({ reason: error.reason })
})
)
})
)
}A Query has the same shape. This is the one every page on this site reads its notes through. Its Layer returns the notes compiled into the bundle, so it answers the same way on the server and in the browser; with a live API, the same declaration would take a Layer that calls it, and nothing that reads it would change.
import { Query } from "@effect/ui";
import { Duration, Effect, Schema } from "effect";
import { Note } from "#domain/Note";
import { allNotes } from "../notes/catalog.ts";
export class ListNotes extends Query.Service<ListNotes>()(
"@the-innovation-lab/frontend/queries/ListNotes",
{ success: Schema.Array(Note), staleTime: Duration.infinity },
) {
static readonly layer = this.toLayer(Effect.succeed(() => Effect.succeed(allNotes)));
}
Server Rendering and Hydration
The same components render on the server and in the browser. On the server, HtmlServer.renderToHtml runs init, update, view and the Queries, and returns the HTML, the head and the state it rendered from. It runs no Command and no Subscription. In the browser, HtmlHydrate takes that state and attaches to the existing markup instead of rendering it again. That only works if the first browser render matches the server's exactly, so anything only the browser knows, such as a saved theme or a measured width, arrives as a message after hydration.
Routes are values too. AppRoute is a union of typed routes: AppRoute.Note({ params: { slug } }) is a route, AppRoute.print turns it into a path and AppRoute.match picks the page for it, one case per route, so a missing case is a type error. The root component holds the current route in its Model and hears every change from Router.subscription. Each page writes its own <head> from a head function.
The server entry is a single call: layerHttp renders the app for any URL its routes parse. Effect UI's Vite plugin asks it for every path in prerender at build and writes the pages out, so the site is static files behind a plain web server.
The browser entry hydrates the whole app with BrowserRouter. From then on a link is a client-side navigation: the router swaps the page, scrolls, moves focus and announces it. Each article is its own chunk through Component.lazy, loaded the first time you open it.
This is the whole server entry for the site: a route list for the build, and layerHttp for everything else.
import type { HtmlServer } from "@effect/ui/html";
import { layerHttp } from "@effect/ui/html/HtmlServerHttp";
import { Array as Arr, Layer, pipe, String as Str } from "effect";
import { FetchHttpClient } from "effect/http";
import { document } from "virtual:@effect/ui/document";
import { renderErrorAttribute } from "#components/RenderError";
import { App } from "./App.ts";
import { allNotes } from "./notes/catalog.ts";
import { AppRoute } from "./routes.ts";
const filters = pipe(
import.meta.env["VITE_PAGES"] ?? "",
Str.split(","),
Arr.map(Str.trim),
Arr.filter(Str.isNonEmpty),
);
const selected = (path: string) =>
Arr.isReadonlyArrayEmpty(filters) ||
Arr.some(filters, (filter) => pipe(path, Str.includes(filter)));
const page = (rendered: HtmlServer.Rendered<unknown>) => {
if (pipe(rendered.html, Str.includes(renderErrorAttribute))) {
throw new Error("a page rendered an error marker instead of its data");
}
return document(rendered);
};
export default layerHttp(App, { routes: AppRoute, document: page, budget: "2 minutes" }).pipe(
Layer.provide(FetchHttpClient.layer),
);
export const prerender = Arr.filter(
[
AppRoute.print(AppRoute.Home()),
AppRoute.print(AppRoute.About()),
AppRoute.print(AppRoute.Resume()),
AppRoute.print(AppRoute.Notes()),
AppRoute.print(AppRoute.PrivacyPolicy()),
AppRoute.print(AppRoute.TermsOfService()),
"/404",
...Arr.map(allNotes, (note) => AppRoute.print(AppRoute.Note({ params: { slug: note.slug } }))),
],
selected,
);
And the browser entry. It provides only platform Layers, the router and the HTTP client, as the guide prescribes; every page provides its own. It loads the current article's chunk before hydrating, so the article's markup is adopted rather than swapped for a loading state.
import { Router } from "@effect/ui";
import { BrowserRouter, HtmlHydrate } from "@effect/ui/html";
import { Effect, Option, Schema } from "effect";
import { FetchHttpClient } from "effect/http";
import { App } from "./App.ts";
import { preloadArticle } from "./notes/components/NoteArticle.ts";
import { AppRoute } from "./routes.ts";
const HydrationState = Schema.StructWithRest(
Schema.Struct({
"~deferred": Schema.String.pipe(Schema.Array, Schema.optional),
"~query": Schema.optional(Schema.Unknown),
"~props": Schema.optional(Schema.Unknown),
"~reported": Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
"~static": Schema.optional(Schema.Boolean),
"~key": Schema.optional(Schema.String),
}),
[Schema.Record(Schema.String, Schema.Unknown)],
);
const element = (id: string) =>
Effect.fromOption(Option.fromNullishOr(document.getElementById(id))).pipe(Effect.orDie);
const hydrate = Effect.gen(function* () {
const container = yield* element("app");
const source = yield* element("state");
const state = yield* Schema.decodeEffect(Schema.fromJsonString(HydrationState))(
source.textContent ?? "",
).pipe(Effect.orDie);
const route = Option.getOrUndefined(AppRoute.parse(window.location.pathname));
if (route !== undefined && route._tag === "Note") {
yield* Effect.promise(() => preloadArticle(route.params.slug));
}
const root = yield* HtmlHydrate.hydrateEffect(App, Router.props(AppRoute), container, state);
yield* root.adopted;
document.documentElement.dataset["hydrated"] = "";
return yield* Effect.never;
}).pipe(
Effect.scoped,
Effect.provide([BrowserRouter.layer({ routes: AppRoute }), FetchHttpClient.layer]),
);
Effect.runFork(hydrate);
Every piece of data a page shows comes from a Query whose Layer works in both places. Notes, images and outlines are plain modules in the bundle; Markdown notes are compiled by Effect UI's Markdown plugin and loaded on demand; code highlighting loads Shiki the first time a page with code needs it. A prerendered page ships the results in its state, and with staleTime: Duration.infinity the browser never fetches them again.
Tests Without a Browser or a Clock
Because update is pure and every effect is data, Effect UI can test a component without running it. It ships three kinds of test, and each one checks something different:
Drives update. Send messages, read the Model, see which Commands and Subscriptions it asked for, and resolve them by hand.
Drives the view the way a person does: click, type and press keys, then check what is on screen by role and accessible name.
Runs the real runtime on a test host, for interactions that cross into a child component, such as arrow keys inside a tab list.
Here is the stopwatch's Story. The clock is a Subscription, so the test does not wait for time to pass or install fake timers. It checks that starting the stopwatch asks for Tick, delivers three ticks itself, and checks that stopping it lets the Subscription go. The last two tests are properties: it.effect.prop generates Models straight from the StopwatchModel Schema.
import { Story } from "@effect/ui/testing";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import { Stopwatch, StopwatchMessage, StopwatchModel } from "./Stopwatch.ts";
describe("Stopwatch", () => {
it.effect("ticks only while it runs, and the clock is just messages", () =>
Effect.gen(function* () {
const s = yield* Story.make(Stopwatch, {});
assert.deepStrictEqual(s.subscriptions, []);
s.send(StopwatchMessage.ClickedStart());
assert.deepStrictEqual(s.subscriptions, ["Tick"]);
s.subscription("Tick", StopwatchMessage.Ticked());
s.subscription("Tick", StopwatchMessage.Ticked());
s.send(StopwatchMessage.ClickedLap());
s.subscription("Tick", StopwatchMessage.Ticked());
s.send(StopwatchMessage.ClickedStop());
assert.deepStrictEqual(s.model, { running: false, tenths: 3, laps: [2] });
assert.deepStrictEqual(s.subscriptions, []);
}),
);
it.effect.prop("reset returns any stopwatch to zero", { model: StopwatchModel }, ({ model }) =>
Effect.gen(function* () {
const s = yield* Story.make(Stopwatch, {});
s.given(model).send(StopwatchMessage.ClickedReset());
assert.deepStrictEqual(s.model, { running: false, tenths: 0, laps: [] });
}),
);
it.effect.prop("a lap while stopped changes nothing", { model: StopwatchModel }, ({ model }) =>
Effect.gen(function* () {
const stopped = { ...model, running: false };
const s = yield* Story.make(Stopwatch, {});
s.given(stopped).send(StopwatchMessage.ClickedLap());
assert.deepStrictEqual(s.model, stopped);
}),
);
});
The tests are strict in a useful way. A test fails if it leaves a Command pending, a Mount unacknowledged or a click ignored without saying so. You cannot leave work dangling and still pass, which catches bugs a looser test would wave through.
When I moved this site onto Effect UI's conventions, I wrote these tests for every demo, and the frontend suite grew from 51 tests to over 350. They found half a dozen real bugs. Two examples: the chatbot let a second message cut off an answer that was still streaming, and the slideshow moved keyboard focus to its Close button every time autoplay was toggled. Both were invisible in screenshots and obvious in a Scene.
How an App Is Organized
Effect UI's guide is specific about layout, and following it made this codebase easier to move around in. Shared types live in domain, queries in queries, shared views in components, and everything else in a folder per feature. There is one page component per route, in folders that mirror the URL. Pages import features; nothing imports a page except the root.
Two smaller rules do a lot of work. domain, queries and components are imported through subpath imports declared once in package.json, such as #domain/Note, which Node, TypeScript, Vite and Vitest all read with no extra config. And a component that provides its own Layers is exported twice: NotePage with its Layers provided, for the app, and NotePageNoDeps without them, so a test can hand it query results directly.
Moving This Site Onto It
This site used to be Astro pages with React components and shadcn/ui: static HTML with the interactive demos hydrated one by one as React components. Now it is one Effect UI app. The server renders it, the build prerenders every route, and the browser hydrates the whole thing, with typed routes and client-side navigation from then on.
The 33 demos across the notes are ordinary child components. The menus, the contact form and the notes search are components with Commands, where they used to be page scripts. Every page's data comes from a Query, and each article is a lazy chunk loaded the first time you open it.
The rule for the move was that nothing could look different. I checked it with full-page screenshots of every route, in light and dark mode, compared pixel by pixel against the previous build, and the end-to-end and accessibility suites ran in both themes before anything shipped.
- One set of types from the database to the button. The Schemas that validate an API payload also describe the state a demo hydrates from.
- Side effects I can read. Every timer, request and DOM measurement is declared in one place per component, and the runtime cleans it up.
- Tests that don't fight the framework. Stories and Scenes need no browser, no fake timers and no mocking library, and they found real bugs.
- Server rendering and hydration come with the framework instead of being bolted onto it.
- It is experimental. It isn't on npm, so this site pins a snapshot of one commit, and upgrades mean reading what changed.
- Views are TypeScript calls, not JSX. Markup-heavy pages get long, and a page of prose is far more code than the same page in Markdown.
- Every page loads the runtime. Hydrating the whole app means Effect and Effect UI arrive with the first page, about 190 KB compressed, where a page of text used to load almost no JavaScript. The browser caches it, and every later page is a client-side navigation.
- There is a learning curve. Choosing between a Command, a Subscription, a Query and a Mount is a real design decision every time.
- Hydration is unforgiving. The server render and the first browser render must match exactly, so anything time- or size-dependent has to arrive as a message. At the commit this site pins, a textarea served with text even comes up empty after hydration, so the Shrinkwrap demo builds its textarea in the browser.
What I took away
- A component is Schemas plus init, update and view. Learn those four and you can read any Effect UI code.
- Every side effect is a Command, a Subscription, a Query or a Mount. Choosing the right one is most of the design work.
- If you already use Effect on the server, the frontend shares its Schemas, services and Layers instead of translating them.
- Stories and Scenes test behaviour without a browser or a clock, and their strictness finds real bugs.
- Use the model it describes: one app, rendered on the server and hydrated in the browser, with typed routes. Everything in the guide assumes it.
- It is experimental. Pin a commit, read the changes before you upgrade, and expect APIs to move.
The bottom line
Effect UI is the most coherent frontend model I have used with Effect: state, effects, rendering and tests all follow from the same few ideas. It is not ready for a team that needs stability. For a site like this one, where I want to build things the way I would build them on the backend, it is the right choice.
Related notes

Agent Harness 101
Every coding agent is a short loop: ask the llm, run the tools it asks for, and stop when it asks for nothing. The harness is everything around that loop that keeps it safe and durable, and each of its primitives (session, thread, turn, tool, permission and agent) is written here as a real schema. Ends with a scripted demo that follows one message from the moment you press enter to the final answer.

Kavita to Obsidian
An Obsidian plugin that syncs reading annotations from Kavita into your vault as searchable markdown. Built with Effect-TS for type-safe error handling, comprehensive testing with 80% coverage, and professional OSS practices including semantic versioning, changelogs, and stress testing for 10,000+ annotations.

Caging Chaos: Building Deterministic AI Chatbots with Effect
Engagement is shifting to chatbots. Users now expect prompt-based interaction. This article shows how to build AI chatbots that feel natural and engaging while remaining deterministic — using Effect-TS for type-safe tools, structured outputs, page-gated behavior, canned responses, and workflow integration.
Get in touch
Have a question about something I wrote, or want to talk? Send me a message.