Effect UI
Effect docsGitHub

// PUBLIC PREVIEW

Introducing Effect UI

Effect UI is a frontend library built on Effect and the Elm Architecture: self-contained Components with explicit state transitions and side effects as values. It continues the work of Foldkit 0.x (foldkit.dev), which we announced as the "new frontend foundation" in Foldkit Joins Effect.

Effect UI is in public preview. If you're building with Foldkit 0.x, the migration will be an upgrade, not a rewrite.

We built this page with Effect UI. You can read its source on GitHub.

Explore with an AI agent

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

What this article covers

Here's how Effect UI works, and the main changes from Foldkit 0.x:

Terms

  • Foldkit 0.x is the existing frontend framework at foldkit.dev.

  • Effect UI is the new frontend library that continues the work of Foldkit 0.x. You import it from @effect/ui.

  • Foldkit is the future full-stack framework. Effect UI will be its frontend.

Components

Foldkit 0.x used the Elm Architecture, with the whole app as one program: one Model, one update and one view. That made every state change easy to follow, but it had costs as an app grew. Every Message ran the view from the root. Every parent stored state and forwarded Messages for its children. No part of an app could load in its own chunk.

Effect UI keeps the Elm Architecture and applies it to each Component. A Component is an Elm Architecture program of its own, and you build an app by composing Components.

Foldkit 0.x

RootModelupdateview
ASubmodel
A1Submodel
A2Submodel

One Model, one update and one view for the whole app. A, A1 and A2 are Submodels inside them.

Effect UI

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.

A Component is self-contained. Its parent doesn't store its state or forward its Messages, so you can write and test it on its own. A Component can provide its own services and load in its own chunk. 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, like Foldkit
// 0.x's defineMessageUnion. 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.

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

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 HTML, while OpenTui.component and OpenTuiCommand.focus in @effect/ui-opentui target the terminal.

How Foldkit 0.x and Effect UI handle Messages

In Foldkit 0.x, every Message went through the root update and re-ran the view from the root. In Effect UI, the runtime delivers a Message straight to its Component's update and re-runs only that Component's view, skipping every parent.

Foldkit 0.x

0/8

Root 
A 
A1 
A2 

Effect UI

0/3

Root 
A 
A1 
A2 

Foldkit 0.x and Effect UI in code

Both examples below build a Page that shows or hides a Counter. A parent no longer stores, wraps or forwards anything for its children. Here, Page drops from 62 lines to 34, and Counter's view only re-runs when its props change.

The appLive

Likes0

Page renders Counter

Counter.tsTypeScript

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 }),

Page.tsTypeScript

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
    })

Organizing larger Components

As a Component grows, you can still move init, update, subscriptions and view into functions of their own. The Component definition's helpers supply their types, so you don't have to annotate them.

Counter.tsTypeScript

import { Subscription } from "@effect/ui"
import { Button } from "@effect/ui-kit"
import { Html } from "@effect/ui/html"
import { Schema, Stream } from "effect"
import { CounterMessage, DelayReset } from "../Counter.ts"

// The definition: the name and the Schemas. Its init, update,
// subscriptions and view helpers type the functions below.
const CounterDef = Html.component({
  name: "Counter",
  model: Schema.Struct({
    count: Schema.Number,
    isAutoCounting: Schema.Boolean
  }),
  message: CounterMessage
})

const init = CounterDef.init(() => ({
}))

// update as one function that matches on the Message, as in
// Foldkit 0.x, instead of a record of handlers.
const update = CounterDef.update(($, message) =>
)

const subscriptions = CounterDef.subscriptions(({ model }) => [
])

const view = CounterDef.view((h, model) =>
)

export const Counter = CounterDef.make({
  init,
  update,
  subscriptions,
  view
})

State and data

Shared state with Providers

In Foldkit 0.x, a shared parent held state that several Submodels needed in its Model. Every parent between them passed that state down. To change it, a Submodel returned an OutMessage, and every parent forwarded it back up to the owner.

In Effect UI, 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 anything 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: () =>

Foldkit 0.x

0/8

Root 
A 
A1 
A2 

Effect UI

0/4

Provider 
A 
A1 
A2 

Data fetching with queries

In Foldkit 0.x, the Model held fetched data, and the parent managed the Query. The parent stored the query state, forwarded its Messages and decided when to load or refresh. In Effect UI, you define a query once and list it on the Components that need it. The runtime fetches the data and keeps it in one cache for every Component.

  • Fetching

    The runtime fetches when the Component renders, and again when the query's arguments change. Setting debounce waits until the arguments stop changing. Until the new result arrives, the last Success stays on screen with waiting: true.

  • 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.

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

The Component lists its query

Posts.tsTypeScript

// 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

Where state is stored

In Foldkit 0.x, one Model held all of an app's state. In Effect UI, state is stored in four places:

StateStored in
A Component's own stateIts own Model
State a parent or a Provider ownsAnother Component's Model
Data a query fetchedThe runtime's query cache
Which Commands are runningThe runtime

A Model holds only the state that its own update changes, not everything the view shows. With logging enabled, you can still replay a Component's recorded Messages, because the log includes what update read from props, queries and Providers.

Views and rendering

Parts for headless Components

Headless Components in Effect UI manage behavior, keyboard handling and ARIA while you write the markup. Instead of returning markup of its own, a headless Component gives your view parts that you apply to your own elements, classes and children. Here, Details renders a Disclosure:

Details.tsTypeScript

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

export const Details = Html.component({
  name: "Details",
  // Nothing to store: Disclosure holds the open state.
  model: Schema.Null,
  message: Schema.Never
}).make({
  init: () => null,
  update: ($) => $.model,
  view: (h) =>
    Disclosure(h, {
      // disclosure holds what Disclosure's parts returns. Each part
      // takes an element written here and returns it with the
      // attributes and handlers it needs.
      view: (disclosure) =>
        h.section.class("details").children(
          disclosure.trigger(h.button).children("Shipping"),
          disclosure.isOpen &&
            disclosure.panel(h.div).children("Arrives in 3 days.")
        )
    })
})

To write one, define parts instead of a view:

Disclosure.tsTypeScript

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

export const Message = UiSchema.TaggedEnum({ ClickedTrigger: {} })

export const Disclosure = Html.component({
  name: "Disclosure",
  model: Schema.Struct({ isOpen: Schema.Boolean }),
  message: Message
}).make({
  init: () => ({ isOpen: false }),
  update: {
    ClickedTrigger: ($) => $.evolve({ isOpen: !$.model.isOpen })
  },
  // parts takes p, the helper that builds parts, as a view takes h,
  // the helper that builds elements. What it returns is what the
  // consumer's view receives: plain values such as isOpen, and parts.
  parts: (p, model) => ({
    isOpen: model.isOpen,
    // p.part makes a part. This one decorates a <button> that the
    // consumer supplies. The click sends Disclosure's own Message to
    // Disclosure's update.
    trigger: p.part("button", (button) =>
      button.attrs({
        type: "button",
        "aria-expanded": String(model.isOpen),
        "aria-controls": p.id("panel")
      }).on("click", Message.ClickedTrigger())),
    panel: p.part("div", (div) => div.id(p.id("panel")))
  })
})

You can package your own reusable behavior the same way.

The UI kit

@effect/ui-kit already ships 41 components, so you don't have to build accessible UI from scratch. The kit has every component in Base UI, plus VirtualList, VirtualKeyboard, DirectionProvider and Positioning. They're all headless. Each handles keyboard, focus and ARIA while you write the markup and styles.

Here is the full set of 41 components. Hover or tap to animate.

  • Accordion
  • AlertDialog
  • Autocomplete
  • Avatar
  • Button
  • Checkbox
  • CheckboxGroup
  • Collapsible
  • Combobox
  • ContextMenu
  • Dialog
  • DirectionProvider
  • Drawer
  • Field
  • Fieldset
  • Form
  • Input
  • Menu
  • Menubar
  • Meter
  • NavigationMenu
  • NumberField
  • OTPField
  • Popover
  • Positioning
  • PreviewCard
  • Progress
  • RadioGroup
  • ScrollArea
  • Select
  • Separator
  • Slider
  • Switch
  • Tabs
  • Toast
  • Toggle
  • ToggleGroup
  • Toolbar
  • Tooltip
  • VirtualKeyboard
  • VirtualList

Host-agnostic rendering

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

Other platforms bring their own elements and host, like @effect/ui-opentui for the terminal, sharing the Component runtime without translating views across platforms. You pick the host when mounting the app, and the host interface is public if you want to write your own.

main.tsTypeScript

import { DevTools } from "@effect/ui-devtools"
import { HtmlHydrate } from "@effect/ui/html"
import { Effect, Layer } from "effect"
import { snippets } from "virtual:snippets"
import { LaunchPage } from "./LaunchPage.ts"

const props = {
  snippets,
  articleUrl: new URL("article.md", document.baseURI).href
}
const root = document.getElementById("root")!
const state = JSON.parse(
  document.getElementById("state")!.textContent!
)

// src/entry.server.ts renders the page, in dev and in the prerendered
// build, and HtmlHydrate.hydrate adopts its DOM nodes. DevTools.layer adds
// the corner inspector.
const Main = HtmlHydrate.hydrate(LaunchPage, props, root, state).pipe(
  Layer.provide(DevTools.layer({ position: "BottomRight" }))
)

// Builds the Layer, which starts the app, and keeps it running.
Layer.launch(Main).pipe(Effect.runFork)

Testing

Story and Scene tests

A Story test sends Messages directly to a Component's update, and a Scene test drives it through the view. You pass the Component, and the test starts from its init Model, or a state you supply with given.

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.

You can also replay a recorded session with Story.fromLog. When logging is enabled, the runtime records every Message a Component receives, along with the props, query results and Provider values its update read. Story.fromLog re-runs those Messages against update without running Commands, and reports the first step where the Component produces a different Model, Command or event.

Play tests

Play is a new kind of test in Effect UI. In Story and Scene tests, you resolve each Command by hand, so the Command itself never runs. A Play test mounts the Component and its children on the test host. It runs their real Commands, Subscriptions and query fetches against the Layers the test provides.

A Play test can cover a whole flow. It clicks a button, lets the real Command run and checks what is on screen afterwards, with no browser and no DOM.

TestClock controls time, so delayed flows run instantly without waiting in real time.

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.

DevTools

Effect UI has an inspector that you add with one Layer, DevTools.layer. 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.

  • 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 gives an agent the same view. It can read the log, inspect a Component's state and show the page at any entry. If you allow it, the agent can also send Messages.

Performance

In js-framework-benchmark, Effect UI scored 4.12× vanilla JavaScript across the nine script operations, compared to 6.55× for Foldkit 0.x. It reached first paint in 381 ms instead of 691 ms, and used 4.1 MB of memory with 1,000 rows instead of 6.1 MB. We ran all seven entries on the same machine.

  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×
  7. Foldkit 0.x 6.55×
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 new

  • 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.

What stays the same

Effect UI keeps these parts of Foldkit 0.x:

  • A constrained, agent-friendly architecture

  • Predictable state changes

  • Side effects as values that the runtime runs

  • Clear, readable tests focused on behavior, not plumbing

  • A Message log you can inspect and replay

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. You can ignore pnpm's unmet @effect/ui peer warning: @effect/ui-kit still uses the snapshot 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.

What happens next

  • Public preview: Effect UI doesn't have everything Foldkit 0.x has yet, and we're sharing it early so you can try the APIs and help shape it.

  • Keep building on Foldkit 0.x: Feature work has moved to Effect UI, and Foldkit 0.x will keep getting critical bug fixes until Effect UI ships with an upgrade guide.

  • Issues and PRs: Development happens in Effect-TS/ui. We'll transfer relevant Foldkit issues and PRs there, so you don't need to open them again.

Thank you to everyone building with Foldkit 0.x. What you've made with it, and what you've told us along the way, is what Effect UI is built on.

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