Effect UI
Effect docsGitHub

// PUBLIC PREVIEW

Introducing Effect UI

Published Updated

Effect UI is a frontend library built on Effect and the Elm Architecture. Build web, terminal and native apps from self-contained Components with explicit state transitions and side effects as values, plus DevTools built for humans and agents.

Effect UI is in public preview. We built this page with it, and you can read its source on GitHub.

Explore with an AI agent

Not reading all that? Copy a prompt to explore Effect UI with an AI agent.

Why Effect UI

Frontend apps get hard for the same reasons everywhere: tangled state, race conditions in async work and side effects scattered across callbacks. Effect UI puts every state transition in one pure function and handles async work, cancellation and errors with Effect. If you also use Effect on the server, the same programming model carries across the whole stack.

Like Effect itself, Effect UI and Effect UI Kit have zero third-party runtime dependencies. Typed routing, a query cache, shared state, server rendering, DevTools, testing harnesses and 52 headless UI modules all come built in, so you don't have to assemble a frontend stack out of half a dozen packages.

Components

A Component is a mini Elm Architecture program, and you build an app by composing Components. Each Component defines its own Model, Messages, update and view. Messages go straight to their Component's update and re-render only that Component.

RootModelupdateview
AModelupdateview
A1Modelupdateview
A2Modelupdateview

Every Component has a Model, an update and a view of its own. Root renders A, and A renders A1 and A2. Props flow down and events flow up.

A Component is self-contained, so you can write, test and lazy-load it on its own, and provide its own services. If a Component fails, the rest of the app keeps running.

Anatomy of a Component

This counter shows the core parts of a Component. One definition holds its Model, Messages, init, update, subscriptions and view.

Counter.tsTypeScript

0
// A Schema union with a constructor for each Message. A Message's
// fields are its payload: ClickedAdd carries the amount to add.
export const CounterMessage = UiSchema.TaggedEnum({
  ClickedAdd: { amount: Schema.Number },
  ClickedResetAfterDelay: {},
  CompletedDelayReset: {},
  ClickedToggleAutoCount: {},
  Ticked: {}
})

// Defines a Command: its name, its options (no args here) and its
// body. DelayReset.make() creates one to run, and the Message its
// Effect returns goes to update.
export const DelayReset = Command.make(

Click "+1", then click the Effect UI button in the bottom-right corner. DevTools lists the Message you sent and what it changed.

Composing Components

This example builds a Page that shows or hides a Counter.

The appLive

Likes0

Page.tsTypeScript

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { Counter } from "./Counter.ts"

const PageMessage = UiSchema.TaggedEnum({
  ClickedToggleCounter: {}
})

export const Page = Html.component({
  name: "Page",
  model: Schema.Struct({ isCounterShown: Schema.Boolean }),
  message: PageMessage
}).make({
  init: () => ({ isCounterShown: true }),
  update: {
    ClickedToggleCounter: ($) => ({
      isCounterShown: !$.model.isCounterShown
    })
  },
  view: (h, model) =>
    h.div.class("counter-page").children(
      h.button
        .on("click", PageMessage.ClickedToggleCounter())
        .children(
          model.isCounterShown ? "Hide counter" : "Show counter"
        ),
      // Calling a Component in the view renders it as a child. The
      // runtime holds its Model until the view stops rendering it.
      // To render two Counters here, give each one a key.
      model.isCounterShown &&
        Counter(h, { props: { label: "Likes" } })
    )
})

Counter.tsTypeScript

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

const CounterMessage = UiSchema.TaggedEnum({
  ClickedDecrement: {},
  ClickedIncrement: {}
})

export const Counter = Html.component({
  name: "Counter",
  // What the parent passes in. init and update read it as $.props
  // and view as h.props.
  props: Schema.Struct({ label: Schema.String }),
  model: Schema.Struct({ count: Schema.Number }),
  message: CounterMessage
}).make({
  init: () => ({ count: 0 }),
  update: {
    // A handler can also return the next Model as a plain value.
    ClickedDecrement: ($) => ({ count: $.model.count - 1 }),
    ClickedIncrement: ($) => ({ count: $.model.count + 1 })
  },
  view: (h, model) =>
    h.div.class("counter").children(
      h.span.class("counter-label").children(h.props.label),
      h.button
        .class("counter-button")
        .attr("aria-label", "Decrement")
        .on("click", CounterMessage.ClickedDecrement())
        .children("-"),
      h.output.class("counter-value").children(String(model.count)),
      h.button
        .class("counter-button")
        .attr("aria-label", "Increment")
        .on("click", CounterMessage.ClickedIncrement())
        .children("+")
    )
})

DevTools

Effect UI has an inspector you can add with one Layer, DevTools.layer, or automatically in dev with DevToolsVite.plugin. It's running on this page, behind the Effect UI button in the bottom-right corner.

  • Timeline

    One list holds every Message from every Component, the Model after it and what changed.

  • Cause and effect

    For any entry, DevTools traces what sent the Message, the Commands it issued and how each one ended.

  • Element picker

    Click Pick to select any element on the page and jump to the Component instance that rendered it. Try it on this page.

  • Noise control

    Stop or resume recording noisy Message tags at runtime without editing code, and surface or filter declared payload fields in the timeline.

  • Time travel

    Pick an earlier entry to see the page at that point. The live app keeps running, and Resume returns to it.

  • For agents

    An MCP server (or WebMCP in the browser) lets agents read the log, inspect Component state and, if allowed, send Messages.

Terminal apps built with @effect/ui-opentui can stream their logs into the same browser inspector with DevToolsHeadless.layer.

Testing

Play tests

A Play test runs a whole user flow without a browser, module mocks or real timers. It mounts a Component and its children on the test host, clicks through the UI, runs real Commands, Subscriptions and Query fetches against in-memory Layers, and checks what's on screen afterwards.

TestClock controls time, so delayed flows run instantly.

Counter.play.test.tsTypeScript

it.effect("resets one second after the click", () =>
  Effect.gen(function*() {
    // Mounts Counter on the test host. After each step, the test
    // waits for the app to finish reacting, so the next line sees
    // the result.
    const play = yield* HtmlPlay.make(Counter, {})
    yield* play.click(addOne)
    yield* play.click(reset)
    yield* TestClock.adjust("999 millis")
    yield* play.expect(count).toHaveText("1")
    yield* TestClock.adjust("1 millis")
    yield* play.expect(count).toHaveText("0")
  }))

Test host treeVisualization

Play tests render nothing and use no browser. This figure sketches the test host's in-memory tree after each line.

Story and Scene tests

To test one Component in isolation without running its Commands, a Story test sends Messages straight to update, and a Scene test drives it through the view. Both start from the Component's init Model or a state you supply with given, and resolve each Command by hand.

Counter.story.test.tsTypeScript

import { Story } from "@effect/ui/testing"
import { assert, it } from "@effect/vitest"
import { Effect } from "effect"
import { Counter, CounterMessage, DelayReset } from "./Counter.ts"

it.effect("resets after the delay", () =>
  Effect.gen(function*() {
    // {} is Counter's props. Each step runs when it is called and
    // returns story, so the steps chain. story.model is the Model
    // after the last one.
    const story = yield* Story.make(Counter, {})
    story.given({ count: 5, isAutoCounting: false })
      .send(CounterMessage.ClickedResetAfterDelay())
      .expectExact(DelayReset)
      .resolve(DelayReset, CounterMessage.CompletedDelayReset())
    assert.strictEqual(story.model.count, 0)
  }))

Counter.scene.test.tsTypeScript

import { HtmlLocator, HtmlScene } from "@effect/ui/html/testing"
import { it } from "@effect/vitest"
import { Effect } from "effect"
import { Counter, CounterMessage, DelayReset } from "./Counter.ts"

const count = HtmlLocator.role("status")
const reset = HtmlLocator.role("button", {
  name: "Reset in 1 second"
})

it.effect("resets after the delay", () =>
  Effect.gen(function*() {
    const scene = yield* HtmlScene.make(Counter, {})
    scene.given({ count: 5, isAutoCounting: false })
      .click(reset)
      .expectExact(DelayReset)
      // Until the test resolves DelayReset, the Command counts as
      // running, so the button reads "Resetting".
      .expect(HtmlLocator.role("button", { name: "Resetting" }))
      .toExist()
      .resolve(DelayReset, CounterMessage.CompletedDelayReset())
      .expect(count).toHaveText("0")
  }))

A test can also supply test values for everything around the Component: a Query's result, a Subscription's value, an event from a child, a Provider's value or new props from the parent.

Story.check runs property tests over Message and Command sequences generated from a Component's Schemas, shrinking any failure to minimal Story steps. For concurrency bugs, Story.explore exhaustively searches overlapping Message and Command settlement orders and reports the shortest failing path.

Effect UI Kit

@effect/ui-kit ships 52 modules, so you don't have to build accessible UI from scratch. Each handles keyboard, focus and ARIA while you write the markup and styles, and you can build your own headless Components the same way.

Of those, 46 are headless components and 5 are lower-level primitives: Dismissal, ListNavigation, Positioning, Typeahead and VirtualKeyboard. The kit covers every component in Base UI, plus Calendar, RangeCalendar, DateField, DatePicker, FileDrop, SortableList, NavigationLinks, VirtualList and DirectionProvider.

Here are all 52 modules. Hover or tap to animate.

  • Accordion
  • AlertDialog
  • Autocomplete
  • Avatar
  • Button
  • Calendar
  • Checkbox
  • CheckboxGroup
  • Collapsible
  • Combobox
  • ContextMenu
  • DateField
  • DatePicker
  • Dialog
  • DirectionProvider
  • Dismissal
  • Drawer
  • Field
  • Fieldset
  • FileDrop
  • Form
  • Input
  • ListNavigation
  • Menu
  • Menubar
  • Meter
  • NavigationLinks
  • NavigationMenu
  • NumberField
  • OTPField
  • Popover
  • Positioning
  • PreviewCard
  • Progress
  • RadioGroup
  • RangeCalendar
  • ScrollArea
  • Select
  • Separator
  • Slider
  • SortableList
  • Switch
  • Tabs
  • Toast
  • Toaster
  • Toggle
  • ToggleGroup
  • Toolbar
  • Tooltip
  • Typeahead
  • VirtualKeyboard
  • VirtualList

Data and state

Data fetching with Queries

Define a Query once and list it on the Components that need it. The runtime fetches the data, shares one cache across every Component and keeps loading and error states out of your Model.

  • Fetching

    Fetches on render and when arguments change, interrupting superseded fetches. Supports debounce and keeps the last result on screen.

  • Caching

    The runtime keeps one result per Query and arguments. Components that ask for the same data share one fetch.

  • Freshness

    A result older than staleTime stays on screen while the runtime refetches it.

  • States

    Each result is an AsyncResult: either no result yet, failure or success.

For live data such as WebSockets or server-sent events, Query.StreamService backs a Query entry with a shared Stream: each emitted value updates the cached result, and the stream closes when nothing watches it.

Also built into Queries

  • polling
  • refetch on focus and reconnect
  • load more
  • invalidation from Commands
  • optimistic updates
  • prefetch on link hover
  • server rendering
  • restore on back and forward

Posts.tsTypeScript

import { Component, Query, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Effect, Schema } from "effect"
import { AsyncResult } from "effect/reactivity"
import { Post, PostsApi } from "../Posts.ts"

// A query caches one result per args; attach its fetcher with `toLayer`.
export class SearchPosts extends Query.Service<SearchPosts>()(
  "SearchPosts",
  {
    args: { search: Schema.String },
    success: Schema.Array(Post),
    error: Schema.String,
    // Stale entries refetch on next use.
    staleTime: "1 minute"
  }
) {
  static readonly layer = this.toLayer(
    Effect.gen(function*() {
      const api = yield* PostsApi
      return ({ search }) => api.search(search)
    })
  )
}

export const PostsMessage = UiSchema.TaggedEnum({
  UpdatedSearch: { search: Schema.String }
})

export const Posts = Html.component({
  name: "Posts",
  model: Schema.Struct({ search: Schema.String }),
  message: PostsMessage,
  queries: {
    posts: {
      query: SearchPosts,
      // The query's args, derived from the Model when it changes.
      args: ({ model }) => ({ search: model.search }),
      // New args wait this long before they fetch, and newer args
      // restart the wait. A fresh cached result is shown at once.
      debounce: "300 millis"
    }
  }
}).make({
  init: () => ({ search: "" }),
  update: { UpdatedSearch: ($, { search }) => $.evolve({ search }) },
  view: (h, model) =>
    h.div.children(
      h.input.attr("aria-label", "Search posts").value(model.search)
        .on("input", ({ value }) =>
          PostsMessage.UpdatedSearch({ search: value })),
      AsyncResult.match(h.queries.posts, {
        onInitial: () =>
          h.p.children("Loading posts"),
        onFailure: () => h.p.children("Could not load posts"),
        // waiting covers both a refetch and a changed search, including debounce.
        onSuccess: ({ value, waiting }) =>
          h.ul.attr("aria-busy", String(waiting)).children(
            value.map((post) =>
              h.li.key(post.id).children(post.title)
            )
          )
      })
    )
  // SearchPosts.layer needs PostsApi, which the app provides.
}).pipe(Component.provide(SearchPosts.layer))

Shared state with Providers

A Provider shares part of its Model with Components inside it, at any depth. Components inside read that state and send the Provider Messages directly, without passing props or callbacks through the parents in between.

CartProvider.tsTypeScript

import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"

export const CartMessage = UiSchema.TaggedEnum({
  RequestedAddItem: {}
})

export const CartProvider = Html.component({
  name: "CartProvider",
  model: Schema.Struct({ count: Schema.Number }),
  message: CartMessage,
  // value is what the Components inside the Provider read. receives
  // lists the Messages they may send it with $.send.
  shares: {
    value: ({ model }) => ({ count: model.count }),
    receives: ["RequestedAddItem"]
  }
}).make({
  init: () => ({ count: 0 }),
  update: {
    RequestedAddItem: ($) => $.evolve({ count: $.model.count + 1 })
  }
})

Shop.tsTypeScript

export const Shop = Html.component({
  name: "Shop",
  // Shop has no state and no Messages.
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    CartProvider(h, {
      // CartProvider draws nothing. Shop passes it this view, and
      // every Component rendered in it, at any depth, is inside the
      // Provider.
      view: () =>

A Provider's Model holds the shared value

0/4

ProviderOwns the value
ANot involved
A1Reads it
A2Reads it

Web, terminal and native

Effect UI renders through a host instead of tying Components to the browser DOM. From the same HTML Components, the browser host renders DOM nodes, the server host writes HTML and the test host builds an in-memory tree.

A Component works the same on every platform. Only the platform-specific pieces change: the view elements, the host you mount onto and the effects that interact with them. For example, Html.component and HtmlCommand.focus target the web, OpenTui.component and OpenTuiCommand.focus in @effect/ui-opentui target the terminal, and Native.component in @effect/ui-native renders React Native views directly through Fabric without React. The host interface is public if you want to build your own.

Performance

In js-framework-benchmark, Effect UI took 4.12× as much JavaScript time as vanilla JavaScript across nine operations (geometric mean). On the same machine, the Effect UI benchmark app reached first paint in 381 ms and used 4.1 MB of memory with 1,000 rows.

  1. Vanilla JS 1.00×
  2. Solid 1.87×
  3. Svelte 2.41×
  4. Vue 3.75×
  5. Effect UI 4.12×
  6. React 6.44×
Geometric mean of JavaScript time across the nine operations, as a multiple of vanilla JavaScript. Shorter is faster. Read the methodology or the raw results.

Also included

  • Typed routing

    Define routes with Schema-typed path and search params in Route, then back navigation with BrowserRouter.layer in the browser, Router.static on the server and Router.memory in tests.

  • Services per Component

    Component.provide gives services to a Component and everything below it. Its Commands and Subscriptions use them, and TypeScript reports a missing service at compile time.

  • Code splitting

    Load a Component from a chunk of its own with Component.lazy. The browser loads the chunk the first time the Component renders, so it stays out of the initial bundle.

  • Control overlapping Commands

    When an update issues a Command that is still running, use concurrent to run both, switch to interrupt the earlier run or queue to wait for it.

  • Full-stack SSR and prerendering

    HtmlServerVite.plugin renders pages on the server in vite dev, prerenders static routes in vite build and can emit a production web handler. This page uses it.

  • Incremental adoption

    Mount any Component into an existing DOM node, publish it as a custom element with BrowserHost.defineElement, or consume third-party Web Components with Html.customElement.

Try a snapshot build

Effect UI isn't on npm yet. Every commit to main is published as a snapshot build on pkg.pr.new. To install the latest one:

pnpm add effect \
  @effect/ui@https://pkg.pr.new/Effect-TS/ui/@effect/ui@main \
  @effect/ui-kit@https://pkg.pr.new/Effect-TS/ui/@effect/ui-kit@main

To stay on one build, replace main with a commit's short SHA. Snapshots of @effect/ui-devtools, @effect/ui-opentui and @effect/ui-native are published the same way, with install commands under Snapshots in the README. You can ignore pnpm's unmet @effect/ui peer warning: the packages still use the snapshots you installed.

To start a new app from Vite's vanilla-ts template, follow Start a new app. @effect/ui ships its guide as node_modules/@effect/ui/AGENTS.md, so point your coding agent's instructions at that file.

The examples in the repository are complete apps you can read and run, including domains (a server-rendered domain search app with a shared HttpApi) and native (an Expo app running on @effect/ui-native).

What happens next

  • Public preview: Effect UI is still experimental, and we're sharing it early so you can try the APIs and help shape them. Open issues and PRs in Effect-TS/ui.

  • Toward full-stack Effect: We're building toward a full-stack Effect framework on the same zero-dependency core, where your database, HTTP and RPC APIs, auth, background work, observability and UI share one programming model. Server rendering and prerendering with a shared HttpApi already work today.

  • Moving into the Effect monorepo: Effect UI lives in its own repository while the APIs settle. Once it's ready, we plan to move it into the main Effect monorepo and version and release it in lockstep with Effect.

  • Coming from Foldkit 0.x? Foldkit 0.x will keep getting critical bug fixes until Effect UI ships with an upgrade guide, and the migration will be an upgrade, not a rewrite. Relevant issues and PRs will move to Effect-TS/ui (read the announcement).

We built this page with Effect UI. Read the source in examples/launch in Effect-TS/ui.