# Trying Effect UI, an Effect-Based UI Library

[Effect UI](https://ui.effect.website) is a UI library built on top of [Effect](https://effect.website/), a library that handles errors and asynchronous work through TypeScript's type system. It adopts the Elm Architecture per component, keeping state transitions inside pure functions while bringing side effects, dependency injection and the test environment into a single model.

In this article, we build a small task management app to walk through the basic structure of Effect UI, asynchronous processing and error handling, and testing.

!> As of December 1, 2026, Effect UI is in Public Preview (an experimental stage) and is not yet published to npm. The API may change in the future.

## What is Effect UI

Effect UI, developed as [Effect-TS/ui](https://github.com/Effect-TS/ui), is a library that defines each component as a small [Elm Architecture](https://guide.elm-lang.org/architecture/) program and composes them into an application.

The Elm Architecture is a UI design pattern that originated in the functional language Elm, and it influenced Redux and React's `useReducer`. It splits rendering and state changes into three parts, `Model`, `view` and `update`, and processes them in a one-way loop in the following order.

1. `view` receives the current `Model` and renders the screen
2. When an interaction such as a button click happens, a `Message` describing what happened is sent to the runtime
3. The runtime passes the current `Model` and the `Message` to `update`, a pure function, and `update` returns "the next `Model`" and "a declaration of the side effects to run (`Command`)" as values
4. The runtime updates the `Model` and re-renders, runs the `Command` if there is one, and passes its result back to `update` as a new `Message`

html> elm-architecture

With React's `useState` and `useEffect`, state updates and asynchronous work tend to scatter across event handlers and effect hooks. In the Elm Architecture, the only entry point for state changes is the pure function `update`. Classic Elm usually has one large `Model` and `update` for the whole app, while Effect UI lets each component have its own.

Effect UI also defines `props`, `Model`, `Message` and `events` all with Effect's `Schema`. From these unified definitions, the framework handles message logging, time travel in DevTools, serialization for server-side rendering (SSR), and input generation in tests.

The main packages of Effect UI are as follows.

- `@effect/ui`: The host-independent core. It provides `@effect/ui/html` for the DOM, type-safe routing, a query cache, Providers, SSR and hydration, test harnesses and more
- `@effect/ui-kit`: A collection of 55 headless UI modules (`Dialog`, `Select`, `Menu`, `Tabs`) that provides ARIA and keyboard interactions with zero external runtime dependencies
- `@effect/ui-devtools`: An inspector with a message log and time travel, which AI agents can also use through MCP to read and operate on state
- `@effect/ui-opentui` / `@effect/ui-native`: Hosts for terminal UIs built with OpenTUI and for native apps that render directly with React Native's Fabric

:::info
Devin Jameson, the author of [Foldkit](https://foldkit.dev/blog/foldkit-joins-effect), an Elm-style framework based on Effect, joined Effectful Technologies in November 2026 as a core maintainer of Effect. Frontend development now happens in Effect UI, which is planned to become the frontend foundation of the full-stack framework Foldkit will provide.
:::

## Setting up the project

We create the task management app with a minimal Vite and TypeScript setup. First, create the project directory and install the dependencies.

Because the Effect UI packages are not yet published to npm, we specify snapshot URLs from [pkg.pr.new](https://pkg.pr.new/~/Effect-TS/ui), which builds a package for each commit on GitHub. For reproducibility, this article pins the commit SHA as of November 30, 2026 (`9a74c82`).

```bash
mkdir try-effect-ui
cd try-effect-ui
npm init -y
```

Set `package.json` to ESM (`"type": "module"`) and add the scripts and dependencies.

```json:package.json
{
  "name": "try-effect-ui",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc --noEmit && vite build",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  },
  "dependencies": {
    "@effect/ui": "https://pkg.pr.new/Effect-TS/ui/@effect/ui@9a74c82",
    "@effect/ui-kit": "https://pkg.pr.new/Effect-TS/ui/@effect/ui-kit@9a74c82",
    "effect": "^4.1.6"
  },
  "devDependencies": {
    "@effect/vitest": "^4.1.6",
    "typescript": "^5.9.3",
    "vite": "^8.3.6",
    "vitest": "^5.1.1"
  }
}
```

Then install the dependencies.

```bash
npm install
```

Next, create `tsconfig.json`. The Effect UI [README](https://github.com/Effect-TS/ui#requirements) lists enabling both `strict: true` and `exactOptionalPropertyTypes: true` as a requirement for every entry point.

```json:tsconfig.json {7-8}
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "strict": true,
    "exactOptionalPropertyTypes": true,
    "noEmit": true,
    "skipLibCheck": true,
    "allowImportingTsExtensions": true,
    "isolatedModules": true
  },
  "include": ["src"]
}
```

Also prepare `index.html` as the mount target.

```html:index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Effect UI Tasks</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
```

## Defining a component with the Elm Architecture

The task management app implements the following three operations.

- Loading the task list asynchronously on startup
- Adding a new task by opening a `Dialog`
- Toggling each task between done and not done

First, define the domain model and typed errors in `src/domain.ts`. A typed error includes the kinds of errors an operation can fail with in the function's return type, so they can be tracked at compile time. For example, if adding a task returns `Effect.Effect<Task, TaskError>`, the type states that "it yields a `Task` on success and a `TaskError` on failure, such as an empty title", which prevents missed error handling. We define these with `Schema`, together with the data carried by Effect UI's state and messages.

```ts:src/domain.ts
import { Schema } from "effect"

export const Task = Schema.Struct({
  id: Schema.String,
  title: Schema.String,
  completed: Schema.Boolean
})

export type Task = typeof Task.Type

export class TaskError extends Schema.TaggedError<TaskError>()("TaskError", {
  reason: Schema.String
}) {}
```

`Task` represents the structure of a single task, and `TaskError` is the typed error for failures in loading, adding or updating tasks. With `Schema.TaggedError`, the error carries `_tag: "TaskError"` and can be tracked at the type level in Effect, so forgetting to handle it becomes a compile error.

### Designing the Model and Message

In Effect UI, a component's `Model` and `Message` are declared with `Schema` and `UiSchema.TaggedEnum`. Under the official naming convention, a `Message` is not a command to change state (such as `AddTask` or `SetLoading`) but a fact about what happened, starting with a past-tense verb. For example, user interactions are `ClickedRetryLoad` or `UpdatedDraftTitle`, and results of asynchronous work are `SucceededAddTask` or `FailedAddTask`. `update` decides how the state changes in response to each fact. The `TaskService` imported at the top is created in the next section.

```ts:src/TaskApp.ts {8-14, 16-29}
import { Command, Component, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Dialog } from "@effect/ui-kit"
import { Effect, Layer, Schema } from "effect"
import { Task } from "./domain.ts"
import { TaskService } from "./TaskService.ts"

export const TaskAppModel = Schema.Struct({
  tasks: Schema.Array(Task),
  loadError: Schema.NullOr(Schema.String),
  dialogOpen: Schema.Boolean,
  draftTitle: Schema.String,
  formError: Schema.NullOr(Schema.String)
})

export const TaskAppMessage = UiSchema.TaggedEnum({
  SucceededLoadTasks: { tasks: Schema.Array(Task) },
  FailedLoadTasks: { reason: Schema.String },
  ClickedRetryLoad: {},
  RequestedOpenAddDialog: {},
  RequestedCloseAddDialog: {},
  UpdatedDraftTitle: { title: Schema.String },
  SubmittedAddTask: {},
  SucceededAddTask: { task: Task },
  FailedAddTask: { reason: Schema.String },
  ClickedToggleTask: { id: Schema.String },
  SucceededToggleTask: { task: Task },
  FailedToggleTask: { reason: Schema.String }
})
```

`TaskAppModel` has no loading flags such as `isLoading` or `isSubmitting`. In Effect UI, `h.isRunning(LoadTasks)` and `h.isRunning(AddTask)` on the `view` argument `h` tell you directly whether a `Command` is running, so you do not need dedicated flags to show a loading indicator or disable a button.

## Handling asynchronous work and errors with `Command.Service` and `Layer`

In the Elm Architecture, `update` is a pure function and never runs I/O or timers directly. Effect UI separates communication with the outside world into Effect's `Context.Service` and `Layer`, and extracts the side effects a component calls into `Command.Service`.

`Context.Service` defines the interface of a service, meaning which operations are available. `Layer` assembles the concrete implementation of how that service actually works and injects it from outside (dependency injection). Separating the definition and implementation of a service with `Layer` lets you swap only the behavior behind it between the browser and tests, without changing the component code at all.

First, create `TaskService` in `src/TaskService.ts`, which loads, adds and toggles tasks. To switch implementations per use case, we prepare the following three `Layer`s.

- `layerBrowser`: For checking the app in the browser. It adds asynchronous delays with `Effect.sleep` so you can see the loading indicator and the button state while submitting
- `layerMemory`: For tests of the happy path and input errors. An in-memory implementation without delays, so tests run fast and deterministically
- `layerFailOnce`: For tests of the load error display and retry. Only the first list load fails with a `TaskError`, and the retry succeeds

```ts:src/TaskService.ts {10-13, 54, 88}
import { Context, Effect, Layer } from "effect"
import { Task, TaskError } from "./domain.ts"

export interface TaskServiceApi {
  readonly list: Effect.Effect<ReadonlyArray<Task>, TaskError>
  add(title: string): Effect.Effect<Task, TaskError>
  toggle(id: string): Effect.Effect<Task, TaskError>
}

export class TaskService extends Context.Service<TaskService, TaskServiceApi>()(
  "app/TaskService"
) {
  static readonly layerBrowser = Layer.sync(TaskService, () => {
    let tasks: Array<Task> = [
      { id: "task-1", title: "Review the basic structure of Effect UI", completed: true },
      { id: "task-2", title: "Write async logic with Command and Layer", completed: false },
      { id: "task-3", title: "Add a Dialog and try it out", completed: false }
    ]
    let nextId = 4

    return TaskService.of({
      list: Effect.gen(function*() {
        yield* Effect.sleep("250 millis")
        return [...tasks]
      }),
      add: (title) =>
        Effect.gen(function*() {
          yield* Effect.sleep("200 millis")
          const trimmed = title.trim()
          if (trimmed.length === 0) {
            return yield* new TaskError({ reason: "Please enter a task name" })
          }
          const created: Task = {
            id: `task-${nextId++}`,
            title: trimmed,
            completed: false
          }
          tasks = [...tasks, created]
          return created
        }),
      toggle: (id) =>
        Effect.gen(function*() {
          const target = tasks.find((task) => task.id === id)
          if (target === undefined) {
            return yield* new TaskError({ reason: "Task not found" })
          }
          const updated: Task = { ...target, completed: !target.completed }
          tasks = tasks.map((task) => (task.id === id ? updated : task))
          return updated
        })
    })
  })

  static readonly layerMemory = (seed: ReadonlyArray<Task>) =>
    Layer.sync(TaskService, () => {
      let tasks: Array<Task> = [...seed]
      let nextId = seed.length + 1

      return TaskService.of({
        list: Effect.sync(() => [...tasks]),
        add: (title) =>
          Effect.suspend(() => {
            const trimmed = title.trim()
            if (trimmed.length === 0) {
              return Effect.fail(new TaskError({ reason: "Please enter a task name" }))
            }
            const created: Task = {
              id: `task-${nextId++}`,
              title: trimmed,
              completed: false
            }
            tasks = [...tasks, created]
            return Effect.succeed(created)
          }),
        toggle: (id) =>
          Effect.suspend(() => {
            const target = tasks.find((task) => task.id === id)
            if (target === undefined) {
              return Effect.fail(new TaskError({ reason: "Task not found" }))
            }
            const updated: Task = { ...target, completed: !target.completed }
            tasks = tasks.map((task) => (task.id === id ? updated : task))
            return Effect.succeed(updated)
          })
      })
    })

  static readonly layerFailOnce = (reason: string, seed: ReadonlyArray<Task>) =>
    Layer.sync(TaskService, () => {
      let failed = false
      let tasks: Array<Task> = [...seed]

      return TaskService.of({
        list: Effect.suspend(() => {
          if (!failed) {
            failed = true
            return Effect.fail(new TaskError({ reason }))
          }
          return Effect.succeed([...tasks])
        }),
        add: (title) =>
          Effect.suspend(() => {
            const created: Task = {
              id: `task-${tasks.length + 1}`,
              title: title.trim(),
              completed: false
            }
            tasks = [...tasks, created]
            return Effect.succeed(created)
          }),
        toggle: (id) =>
          Effect.suspend(() => {
            const target = tasks.find((task) => task.id === id)
            if (target === undefined) {
              return Effect.fail(new TaskError({ reason: "Task not found" }))
            }
            const updated: Task = { ...target, completed: !target.completed }
            tasks = tasks.map((task) => (task.id === id ? updated : task))
            return Effect.succeed(updated)
          })
      })
    })
}
```

`Layer.sync` runs a synchronous function to create a new service each time the `Layer` is built. The tests later pass `{ buildPerTest: true }` to `it.layer` so the `Layer` is rebuilt for every test, which means each test starts from the initial `tasks`.

`Effect.suspend`, used in `layerMemory` and `layerFailOnce`, defers evaluation until the Effect runs. It makes the code read the latest `tasks` when the runtime actually runs it, not at the moment the method is called.

Next, use `Command.Service` to add the side effects that call `TaskService` from the component to the end of `src/TaskApp.ts`. `Command.Service` is a class that declares the specification of a side effect a component asks the runtime to perform, and separates the actual implementation into a `Layer`. Because the component only returns `Command`s as values instead of calling `TaskService` directly, the tests later can stop the side effects or swap their implementation.

```ts:src/TaskApp.ts {1-7, 8, 13-16, 25-27}
export class LoadTasks extends Command.Service<LoadTasks>()(
  "tasks/LoadTasks",
  {
    success: TaskAppMessage,
    mode: "switch"
  }
) {
  static readonly layer = this.toLayer(
    Effect.gen(function*() {
      const service = yield* TaskService
      return () =>
        service.list.pipe(
          Effect.match({
            onSuccess: (tasks) => TaskAppMessage.SucceededLoadTasks({ tasks }),
            onFailure: (error) => TaskAppMessage.FailedLoadTasks({ reason: error.reason })
          })
        )
    })
  )
}

export class AddTask extends Command.Service<AddTask>()(
  "tasks/AddTask",
  {
    args: { title: Schema.String },
    success: TaskAppMessage,
    mode: "queue"
  }
) {
  static readonly layer = this.toLayer(
    Effect.gen(function*() {
      const service = yield* TaskService
      return ({ title }) =>
        service.add(title).pipe(
          Effect.match({
            onSuccess: (task) => TaskAppMessage.SucceededAddTask({ task }),
            onFailure: (error) => TaskAppMessage.FailedAddTask({ reason: error.reason })
          })
        )
    })
  )
}

export class ToggleTask extends Command.Service<ToggleTask>()(
  "tasks/ToggleTask",
  {
    args: { id: Schema.String },
    success: TaskAppMessage,
    mode: "queue"
  }
) {
  static readonly layer = this.toLayer(
    Effect.gen(function*() {
      const service = yield* TaskService
      return ({ id }) =>
        service.toggle(id).pipe(
          Effect.match({
            onSuccess: (task) => TaskAppMessage.SucceededToggleTask({ task }),
            onFailure: (error) => TaskAppMessage.FailedToggleTask({ reason: error.reason })
          })
        )
    })
  )
}
```

A `Command.Service` definition has two parts: the "declaration of the specification" in the first half and the "binding of the implementation (`this.toLayer`)" in the second half.

The options in the first half specify the inputs and outputs of the side effect and its concurrency rule.

- `args`: The `Schema` of the arguments passed when the `Command` runs
- `success`: The `Schema` of the result returned to the runtime when the work completes
- `mode`: The concurrency control when the same `Command` is issued more than once. `"switch"` on `LoadTasks` automatically interrupts the earlier run and keeps the new one, `"queue"` on `AddTask` and `ToggleTask` processes runs one at a time after the earlier one finishes, and the default `"concurrent"` runs them all in parallel

`this.toLayer(...)` in the second half is a method that binds the actual implementation to the declared specification and produces a `Layer` that provides it to components. When the `Layer` is built, it takes the dependency out with `yield* TaskService` and returns a function that receives the arguments and does the work.

Inside `this.toLayer(...)`, `Effect.match` converts both success and failure into a `Message`. If you forget to convert a `TaskError` into a `Message`, TypeScript detects the unhandled error and reports a compile error at `this.toLayer(...)`.

## Defining the initial state and state transitions with `init` and `update`

Effect UI keeps rendering, state updates and calls to asynchronous work inside a single, independent component. Because it does not depend on the state of a parent screen or the whole app, you can take the component out and test it on its own, or drop it into another screen as is. A DOM component is defined by passing a name and `Schema`s to `Html.component`, and is built with HTML element builders such as `h.div` and `h.button`.

A component's behavior is first defined with `init` and `update`.

- `init`: A function that returns the initial state (`Model`) when the component first mounts, along with any `Command` to run on startup. Here it sets an empty task list and issues `LoadTasks` to load the initial data
- `update`: A pure function that returns, for each incoming `Message`, "how to change the current `Model`" and "any additional `Command` to issue". For example, on `SubmittedAddTask` it issues `AddTask`, and when `SucceededAddTask` comes back it appends the task to the list and closes the dialog

Using the `Model`, `Message` and `Command`s defined so far, append the following to the end of `src/TaskApp.ts`. So that unit tests can use it as is, we define it here as `TaskAppNoDeps`, before the `Command` implementation `Layer`s are bound.

```ts:src/TaskApp.ts {8-15, 30-33, 43-44}
const TaskAppDef = Html.component({
  name: "TaskApp",
  model: TaskAppModel,
  message: TaskAppMessage
})

export const TaskAppNoDeps = TaskAppDef.make({
  init: ($) =>
    $.set({
      tasks: [],
      loadError: null,
      dialogOpen: false,
      draftTitle: "",
      formError: null
    }).run(LoadTasks.make()),

  update: {
    SucceededLoadTasks: ($, { tasks }) =>
      $.evolve({ tasks, loadError: null }),
    FailedLoadTasks: ($, { reason }) =>
      $.evolve({ loadError: reason }),
    ClickedRetryLoad: ($) =>
      $.evolve({ loadError: null }).run(LoadTasks.make()),
    RequestedOpenAddDialog: ($) =>
      $.evolve({ dialogOpen: true, draftTitle: "", formError: null }),
    RequestedCloseAddDialog: ($) =>
      $.evolve({ dialogOpen: false, formError: null }),
    UpdatedDraftTitle: ($, { title }) =>
      $.evolve({ draftTitle: title, formError: null }),
    SubmittedAddTask: ($) =>
      $.evolve({ formError: null }).run(
        AddTask.make({ title: $.model.draftTitle })
      ),
    SucceededAddTask: ($, { task }) =>
      $.evolve({
        tasks: (tasks) => [...tasks, task],
        dialogOpen: false,
        draftTitle: "",
        formError: null
      }),
    FailedAddTask: ($, { reason }) =>
      $.evolve({ formError: reason }),
    ClickedToggleTask: ($, { id }) =>
      $.run(ToggleTask.make({ id })),
    SucceededToggleTask: ($, { task }) =>
      $.evolve({
        tasks: (tasks) =>
          tasks.map((current) => (current.id === task.id ? task : current))
      }),
    FailedToggleTask: ($, { reason }) =>
      $.evolve({ loadError: reason })
  },
  // The view is written in the next section
```

`update` is written as an object with a handler per message tag. If even one tag defined in `TaskAppMessage` is missing, it is a compile error, so the type checker catches missing handlers. State updates use `$.evolve(...)`, which takes only the fields you want to change. Chaining `.run(...)` onto the result declares a `Command` to issue together with the state update.

## Implementing `view` with the HTML builder

Next, implement `view`, which renders the screen. Effect UI's `view` uses neither JSX nor a custom template syntax. Instead, you build elements with method chains on the HTML builder `h` passed as the first argument, as in `h.button.attr(...).class(...).on("click", ...).children(...)`. Attribute values and event payloads are strictly typed in TypeScript, and the running state of a `Command` is also available through the builder, as in `h.isRunning(LoadTasks)`.

Inside this `view`, we use the [`Dialog`](https://github.com/Effect-TS/ui/blob/main/packages/ui-kit/src/Dialog.ts) from `@effect/ui-kit` for the modal that adds a new task. `Dialog` is a headless UI without styles. The library handles only behavior such as accessibility and focus management, and the caller writes the markup and styles freely with the `h` builder.

At the `// The view is written in the next section` line in `src/TaskApp.ts`, continue with `view` and the `TaskApp` export.

```ts:src/TaskApp.ts {5-11, 17-24, 31-43, 84-90}
  view: (h, model) =>
    h.main.class("app").children(
      h.header.class("app-header").children(
        h.h1("Tasks"),
        Dialog(h, {
          props: { open: model.dialogOpen },
          onEmit: {
            RequestedOpen: () => TaskAppMessage.RequestedOpenAddDialog(),
            RequestedClose: () => TaskAppMessage.RequestedCloseAddDialog(),
            Settled: () => undefined
          },
          view: (dialog) =>
            h.div(
              dialog.trigger(
                h.button.attr("type", "button").class("primary-button")
              ).children("Add task"),
              dialog.portal(h.div)?.children(
                dialog.backdrop(h.div.class("dialog-backdrop")),
                dialog.viewport(h.div.class("dialog-viewport")).children(
                  dialog.popup(h.div.class("dialog-popup")).children(
                    dialog.title(h.h2.class("dialog-title")).children("New task"),
                    dialog.description(h.p.class("dialog-description")).children(
                      "Enter a task name and press Add."
                    ),
                    h.form.class("dialog-form").on(
                      "submit",
                      TaskAppMessage.SubmittedAddTask()
                    ).children(
                      h.label.class("field-label").children(
                        "Task name",
                        dialog.initialFocus(
                          h.input
                            .attrs({
                              type: "text",
                              name: "title",
                              placeholder: "e.g. Write tests"
                            })
                            .class("text-input")
                            .value(model.draftTitle)
                            .on("input", ({ value }) =>
                              TaskAppMessage.UpdatedDraftTitle({ title: value })
                            )
                        )
                      ),
                      model.formError !== null &&
                        h.p.attr("role", "alert").class("error-message").children(
                          model.formError
                        ),
                      h.div.class("dialog-actions").children(
                        dialog.close(
                          h.button.attr("type", "button").class("secondary-button")
                        ).children("Cancel"),
                        h.button
                          .attr("type", "submit")
                          .class("primary-button")
                          .disabled(h.isRunning(AddTask))
                          .children(h.isRunning(AddTask) ? "Adding..." : "Add")
                      )
                    )
                  )
                )
              )
            )
        })
      ),

      h.isRunning(LoadTasks) &&
        h.p.attr("role", "status").class("status-message").children("Loading..."),

      model.loadError !== null &&
        h.div.class("error-banner").children(
          h.p.attr("role", "alert").children(model.loadError),
          h.button
            .attr("type", "button")
            .class("secondary-button")
            .on("click", TaskAppMessage.ClickedRetryLoad())
            .children("Retry")
        ),

      !h.isRunning(LoadTasks) && model.loadError === null &&
        h.ul.class("task-list").children(
          ...model.tasks.map((task) =>
            h.li.key(task.id).class("task-item", task.completed && "completed").children(
              h.button
                .attr("type", "button")
                .attr("aria-label", `Toggle completion of ${task.title}`)
                .attr("aria-pressed", task.completed ? "true" : "false")
                .class("task-toggle")
                .on("click", TaskAppMessage.ClickedToggleTask({ id: task.id }))
                .children(task.completed ? "Done" : "Not done"),
              h.span.class("task-title").children(task.title)
            )
          )
        )
    )
})
```

This code shows several constructs specific to Effect UI's `view`.

- `h.isRunning(LoadTasks)` / `h.isRunning(AddTask)`: Returns a `boolean` telling whether the `Command` is running or waiting in the queue. You can show a loading message or control the submit button's `.disabled(...)` without a flag like `isLoading` in the `Model`
- `.class("task-item", task.completed && "completed")`: `.class(...)` takes multiple arguments and ignores `false`, `null` and `undefined`
- `h.h1("Tasks")`: Elements that need no attributes or events can be called directly without `.children(...)`
- `h.form.on("submit", ...)` and `h.input.on("input", ({ value }) => ...)`: An event handler takes either a `Message` itself or a function that returns a `Message` from a prepared payload. `submit` calls `preventDefault` by default, and `input` receives `{ value }` directly instead of the raw DOM event
- `h.button.attr("aria-pressed", ...)`: The allowed value type is fixed per attribute name, and any value other than `"true" | "false" | "mixed"` (`AriaTristate`) for `aria-pressed` is a compile error
- `dialog.portal(h.div)?.children(...)`: `dialog.portal(h.div)` returns `undefined` while the dialog is closed, so optional chaining shows and hides it as is

Finally, use `Component.provide` to bind each `Command`'s implementation `Layer` to `TaskAppNoDeps`. Leaving only the `TaskService` `Layer` to be passed from outside lets you swap the implementation between integration tests and the browser.

```ts:src/TaskApp.ts
export const TaskApp = TaskAppNoDeps.pipe(
  Component.provide(
    Layer.mergeAll(LoadTasks.layer, AddTask.layer, ToggleTask.layer)
  )
)
```

Lastly, create the code that mounts the app in the browser, along with minimal styles.

```ts:src/main.ts
import { BrowserHost } from "@effect/ui/html"
import { Effect, Layer } from "effect"
import { TaskApp } from "./TaskApp.ts"
import { TaskService } from "./TaskService.ts"
import "./styles.css"

const Main = BrowserHost.mount(
  TaskApp,
  {},
  document.getElementById("app")!
).pipe(Layer.provide(TaskService.layerBrowser))

Layer.launch(Main).pipe(Effect.runFork)
```

<details>
<summary>Code for <code>src/styles.css</code></summary>

```css:src/styles.css {126-138}
:root {
  color-scheme: light;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  line-height: 1.5;
  color: #1f2937;
  background-color: #f9fafb;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 2rem 1rem;
}

.app {
  max-width: 600px;
  margin: 0 auto;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 1.5rem;
}

.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  margin-bottom: 1.25rem;
}

.app-header h1 {
  margin: 0;
  font-size: 1.375rem;
}

.primary-button,
.secondary-button,
.task-toggle {
  font: inherit;
  border-radius: 8px;
  padding: 0.5rem 0.9rem;
  cursor: pointer;
}

.primary-button {
  background: #111827;
  color: #ffffff;
  border: 1px solid #111827;
}

.primary-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.secondary-button {
  background: #ffffff;
  color: #374151;
  border: 1px solid #d1d5db;
}

.task-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: grid;
  gap: 0.75rem;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.task-item.completed .task-title {
  text-decoration: line-through;
  color: #6b7280;
}

.task-toggle {
  min-width: 4.5rem;
  font-size: 0.875rem;
  background: #f3f4f6;
  border: 1px solid #d1d5db;
  color: #111827;
}

.task-item.completed .task-toggle {
  background: #ecfdf5;
  border-color: #6ee7b7;
  color: #065f46;
}

.status-message {
  color: #4b5563;
  margin: 1rem 0;
}

.error-banner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 0.75rem 1rem;
  border-radius: 8px;
  background: #fef2f2;
  border: 1px solid #fecaca;
  color: #991b1b;
}

.error-banner p,
.error-message {
  margin: 0;
  color: #b91c1c;
  font-size: 0.875rem;
}

.dialog-backdrop {
  position: fixed;
  inset: 0;
  background: rgba(17, 24, 39, 0.45);
}

.dialog-viewport {
  position: fixed;
  inset: 0;
  display: grid;
  place-items: center;
  padding: 1rem;
}

.dialog-popup {
  width: min(440px, 100%);
  background: #ffffff;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.16);
}

.dialog-title {
  margin: 0 0 0.5rem;
  font-size: 1.125rem;
}

.dialog-description {
  margin: 0 0 1rem;
  color: #4b5563;
  font-size: 0.9rem;
}

.dialog-form {
  display: grid;
  gap: 0.85rem;
}

.field-label {
  display: grid;
  gap: 0.4rem;
  font-size: 0.9rem;
  font-weight: 500;
}

.text-input {
  font: inherit;
  padding: 0.55rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 8px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
  margin-top: 0.25rem;
}
```

</details>

## Testing state transitions and asynchronous work with `Story` and `HtmlPlay`

Effect UI includes test harnesses in the library itself, so you do not need to combine external libraries. The official documentation, [Testing `@effect/ui` components](https://github.com/Effect-TS/ui/blob/main/ai-docs/src/10_ui/50_testing.ts), uses three kinds depending on the granularity you want to test.

- `Story`: Starts neither the view nor the runtime. It sends `Message`s directly to `update` and checks the `Model` changes and issued `Command`s as a pure function
- `HtmlScene`: Sends clicks and input to the `view` of a single component and checks the rendered output and issued `Command`s
- `HtmlPlay` + `TestHost`: Mounts the component with its children and `Layer`s on an in-memory virtual host, and checks a sequence of user interactions while running real `Command`s against test `Layer`s

Here, we write and run two tests: a unit test of state transitions with `Story`, and an integration test with `HtmlPlay` + `TestHost`.

### Checking pure state transitions and issued `Command`s with `Story`

In `src/TaskApp.story.test.ts`, we use `TaskAppNoDeps`, before any `Layer` is injected, and combine the following methods to check state transitions.

- `Story.make`: Runs the component's `init` and creates an instance to operate on and observe in the test
- `send`: Sends a `Message` to `update` and advances the state by one step. The updated state is available from `s.model`, and the `Command`s returned by `update` are not run but stay pending
- `expectExact`: Checks that the pending `Command` is of the expected kind
- `resolve`: Manually returns a result `Message` for a pending `Command` and advances the following `update`

```ts:src/TaskApp.story.test.ts {19-23, 31-35}
import { Story } from "@effect/ui/testing"
import { assert, describe, it } from "@effect/vitest"
import { Effect } from "effect"
import type { Task } from "./domain.ts"
import {
  AddTask,
  LoadTasks,
  TaskAppMessage,
  TaskAppNoDeps
} from "./TaskApp.ts"

const initialTasks: ReadonlyArray<Task> = [
  { id: "task-1", title: "Read the spec", completed: false }
]

describe("TaskApp Story", () => {
  it.effect("transitions from the initial load to adding a task", () =>
    Effect.gen(function*() {
      const s = yield* Story.make(TaskAppNoDeps, {})

      s.expectExact(LoadTasks)
      s.resolve(LoadTasks, TaskAppMessage.SucceededLoadTasks({ tasks: initialTasks }))
      assert.deepStrictEqual(s.model.tasks, initialTasks)

      s.send(TaskAppMessage.RequestedOpenAddDialog())
      assert.isTrue(s.model.dialogOpen)

      s.send(TaskAppMessage.UpdatedDraftTitle({ title: "Write tests" }))
      assert.strictEqual(s.model.draftTitle, "Write tests")

      s.send(TaskAppMessage.SubmittedAddTask()).expectExact(AddTask)
      assert.deepStrictEqual(s.pending[0]?.command.args, { title: "Write tests" })

      const created: Task = { id: "task-2", title: "Write tests", completed: false }
      s.resolve(AddTask, TaskAppMessage.SucceededAddTask({ task: created }))

      assert.isFalse(s.model.dialogOpen)
      assert.strictEqual(s.model.draftTitle, "")
      assert.strictEqual(s.model.tasks.length, 2)
      assert.deepStrictEqual(s.model.tasks[1], created)
    })
  )

  it.effect("keeps the dialog open with the error when adding a task fails", () =>
    Effect.gen(function*() {
      const s = yield* Story.make(TaskAppNoDeps, {})
      s.expectExact(LoadTasks).resolve(
        LoadTasks,
        TaskAppMessage.SucceededLoadTasks({ tasks: [] })
      )

      s.send(TaskAppMessage.RequestedOpenAddDialog())
      s.send(TaskAppMessage.SubmittedAddTask()).expectExact(AddTask)
      s.resolve(
        AddTask,
        TaskAppMessage.FailedAddTask({ reason: "Please enter a task name" })
      )

      assert.isTrue(s.model.dialogOpen)
      assert.strictEqual(s.model.formError, "Please enter a task name")
    })
  )
})
```

`Story.make` runs as a scoped Effect and fails the test automatically if unresolved `Command`s or unacknowledged events remain when the test ends. For example, leaving the `LoadTasks` issued by `init` without `resolve` fails the test, which catches unintended gaps in state transitions.

### Checking user interactions with `HtmlPlay` and test `Layer`s

Next, create `src/TaskApp.play.test.ts`. By composing `TaskService.layerMemory` or `TaskService.layerFailOnce` with `TestHost.layer()` and passing it to `it.layer` from `@effect/vitest`, you can test a sequence of interactions without a browser and without module mocks such as `vi.mock`. The tests mainly use the following methods.

- `HtmlPlay.make`: Mounts the component on the virtual host and creates an instance for interaction and assertions
- `HtmlLocator.role` / `Locator.text`: Specifies the target element by ARIA role and accessible name, or by text
- `play.click` / `play.type`: Sends a click or text input to an element and waits for `Command`s to complete and the view to re-render
- `play.expect`: Checks whether an element is present or absent, its text, its attributes and so on

```ts:src/TaskApp.play.test.ts {13-16, 23-29, 67-72}
import { HtmlLocator, HtmlPlay } from "@effect/ui/html/testing"
import { Locator, TestHost } from "@effect/ui/testing"
import { it } from "@effect/vitest"
import { Effect, Layer } from "effect"
import type { Task } from "./domain.ts"
import { TaskApp } from "./TaskApp.ts"
import { TaskService } from "./TaskService.ts"

const seedTasks: ReadonlyArray<Task> = [
  { id: "task-1", title: "Read the spec", completed: false }
]

it.layer(
  TaskService.layerMemory(seedTasks).pipe(Layer.provideMerge(TestHost.layer())),
  { buildPerTest: true }
)("TaskApp Play (happy path and input errors)", (it) => {
  it.effect("opens the Dialog, adds a task, and toggles its completion", () =>
    Effect.gen(function*() {
      const play = yield* HtmlPlay.make(TaskApp, {})

      yield* play.expect(Locator.text("Read the spec")).toExist()

      yield* play.click(HtmlLocator.role("button", { name: "Add task" }))
      const dialog = HtmlLocator.role("dialog", { name: "New task" })
      yield* play.expect(dialog).toExist()

      const input = HtmlLocator.role("textbox", { name: "Task name" })
      yield* play.type(input, "Write Play tests")
      yield* play.click(HtmlLocator.role("button", { name: "Add" }))

      yield* play.expect(dialog).toBeAbsent()
      yield* play.expect(Locator.text("Write Play tests")).toExist()

      const toggleButton = HtmlLocator.role("button", {
        name: "Toggle completion of Read the spec"
      })
      yield* play.expect(toggleButton).toHaveAttributes({
        "aria-pressed": "false"
      })
      yield* play.click(toggleButton)
      yield* play.expect(toggleButton).toHaveAttributes({
        "aria-pressed": "true"
      })
    })
  )

  it.effect("shows an error in the dialog for an empty title and closes on Cancel", () =>
    Effect.gen(function*() {
      const play = yield* HtmlPlay.make(TaskApp, {})
      const dialog = HtmlLocator.role("dialog", { name: "New task" })

      yield* play.click(HtmlLocator.role("button", { name: "Add task" }))
      yield* play.expect(dialog).toExist()

      yield* play.click(HtmlLocator.role("button", { name: "Add" }))
      yield* play.expect(HtmlLocator.role("alert")).toHaveText(
        "Please enter a task name"
      )
      yield* play.expect(dialog).toExist()

      yield* play.click(HtmlLocator.role("button", { name: "Cancel" }))
      yield* play.expect(dialog).toBeAbsent()
    })
  )
})

it.layer(
  TaskService.layerFailOnce("Failed to load the task list", seedTasks).pipe(
    Layer.provideMerge(TestHost.layer())
  ),
  { buildPerTest: true }
)("TaskApp Play (load failure and retry)", (it) => {
  it.effect("shows the list after retrying a failed initial load", () =>
    Effect.gen(function*() {
      const play = yield* HtmlPlay.make(TaskApp, {})

      yield* play.expect(HtmlLocator.role("alert")).toHaveText(
        "Failed to load the task list"
      )

      yield* play.click(HtmlLocator.role("button", { name: "Retry" }))
      yield* play.expect(HtmlLocator.role("alert")).toBeAbsent()
      yield* play.expect(Locator.text("Read the spec")).toExist()
    })
  )
})
```

Run the type check and Vitest. No Vitest configuration file is needed.

```bash
npm run typecheck
npm test
```

Running them locally, all tests pass as shown below.

```text
 ✓ src/TaskApp.story.test.ts (2 tests) 7ms
 ✓ src/TaskApp.play.test.ts (3 tests) 43ms

 Test Files  2 passed (2)
      Tests  5 passed (5)
   Start at  20:02:33
   Duration  474ms
```

## Checking it in the browser

Finally, start the development server and check the app in a real browser.

```bash
npm run dev
```

After the loading indicator, the three initial tasks appear. Pressing the "Add task" button at the top right opens a modal with a form to add a task. The screenshots below were taken with the Japanese version of the UI text.

![The add-task dialog is open, with initial focus on the task name field](https://images.ctfassets.net/in6v9lxmm5c8/7KfvQBK1VviOV7eRbeyz6r/abb10db6b278e8f53e2d2d4bc4172ce7/try-effect-ui-1.png)

Adding tasks and toggling them to done also worked as expected.

![A fourth task has been added, and the second task has been switched to done](https://images.ctfassets.net/in6v9lxmm5c8/5RfvihFtIkY5Mx8QTGubCm/6d4f12d44b9b3be104b909ee1efd24ff/try-effect-ui-2.png)

## Summary

- Effect UI adopts the Elm Architecture per component, keeping state transitions in the pure function `update` while building them type-safely with Effect's `Schema`
- Asynchronous work and external services are separated with `Command.Service` and `Layer`, so the type checker prevents missed error handling and the implementation can be swapped per environment
- `view` is written with a typed HTML builder instead of JSX, and `@effect/ui-kit` brings accessible headless UI into the same design
- With the built-in test harnesses (`Story` and `HtmlPlay`), passing test `Layer`s is enough to check everything from state transitions to user interactions quickly without a browser

## References

- [Effect UI](https://ui.effect.website)
- [Effect-TS/ui - GitHub](https://github.com/Effect-TS/ui)
- [Testing `@effect/ui` components - Effect-TS/ui](https://github.com/Effect-TS/ui/blob/main/ai-docs/src/10_ui/50_testing.ts)
- [@effect/ui-kit README - Effect-TS/ui](https://github.com/Effect-TS/ui/blob/main/packages/ui-kit/README.md)
- [Dialog.ts - @effect/ui-kit](https://github.com/Effect-TS/ui/blob/main/packages/ui-kit/src/Dialog.ts)
- [Foldkit Joins Effect - Foldkit Blog](https://foldkit.dev/blog/foldkit-joins-effect)
- [Effect-TS: A TypeScript library for handling errors and asynchronous work more safely (Japanese)](https://azukiazusa.dev/blog/typescript-library-for-safer-error-handling-and-async-operations-effect-ts/)
  