# 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](https://foldkit.dev)), which we announced as the "new frontend foundation" in [Foldkit Joins Effect](https://foldkit.dev/blog/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](https://github.com/Effect-TS/ui/tree/main/examples/launch) on GitHub.

## What this article covers

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

- [Components](#components)
- [State and data](#state-and-data)
- [Views and rendering](#views-and-rendering)
- [Testing](#testing)
- [DevTools](#devtools)
- [Performance](#performance)

## Terms

- **Foldkit 0.x** is the existing frontend framework at [foldkit.dev](https://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.** One Model, one update and one view for the whole app. A, A1 and A2 are Submodels inside them.

**Effect UI.** 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.ts`

```ts
import { Command, Subscription, UiSchema } from "@effect/ui"
import { Button } from "@effect/ui-kit"
import { Html } from "@effect/ui/html"
import { Effect, Schema, Stream } from "effect"

// 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.
export const DelayReset = Command.make(
  "DelayReset",
  {},
  () =>
    Effect.sleep("1 second").pipe(
      Effect.as(CounterMessage.CompletedDelayReset())
    )
)

// Html.component defines a Component whose view builds HTML
// elements, such as h.div.
export const Counter = Html.component({
  name: "Counter",
  model: Schema.Struct({
    count: Schema.Number,
    isAutoCounting: Schema.Boolean
  }),
  message: CounterMessage
}).make({
  init: () => ({ count: 0, isAutoCounting: false }),
  // A handler per Message. $ holds the current Model and builds
  // the result: $.evolve changes the fields it names, and $.run
  // issues a Command. Foldkit 0.x returned { model, commands }.
  update: {
    // The Message's payload is the handler's second argument.
    ClickedAdd: ($, { amount }) =>
      $.evolve({ count: (count) => count + amount }),
    // Runs the Command without changing the Model. To do both,
    // chain them: $.evolve({ ... }).run(...). In Foldkit 0.x,
    // update returned { model, commands } instead.
    ClickedResetAfterDelay: ($) => $.run(DelayReset.make()),
    CompletedDelayReset: ($) => $.evolve({ count: 0 }),
    ClickedToggleAutoCount: ($) =>
      $.evolve({
        isAutoCounting: (isAutoCounting) => !isAutoCounting
      }),
    Ticked: ($) => $.evolve({ count: (count) => count + 1 })
  },
  // Called on mount and after each update. A Subscription's
  // Stream runs while its key, "tick", is listed, and each value
  // it emits is sent as a Message. A false entry is skipped.
  subscriptions: ({ model }) => [
    model.isAutoCounting &&
    Subscription.make(
      "tick",
      Stream.tick("1 second").pipe(
        // Stream.tick emits once at the start. Skip that one.
        Stream.drop(1),
        Stream.map(() => CounterMessage.Ticked())
      )
    )
  ],
  view: (h, model) =>
    h.div.class("counter").children(
      h.output.class("counter-value").children(String(model.count)),
      // Button is a view function from the UI kit, not a Component.
      // It returns a <button> builder, and a press sends onPress.
      Button(h, {
        onPress: CounterMessage.ClickedAdd({ amount: -1 })
      })
        .class("counter-button counter-add")
        .children("−1"),
      Button(h, { onPress: CounterMessage.ClickedAdd({ amount: 1 }) })
        .class("counter-button counter-add")
        .children("+1"),
      Button(h, {
        props: {
          // h.isRunning is true while a DelayReset Command is
          // running. The runtime tracks that, so the Model doesn't
          // need a flag for it.
          disabled: h.isRunning(DelayReset),
          // Keeps keyboard focus on the button while it's disabled.
          focusableWhenDisabled: true
        },
        onPress: CounterMessage.ClickedResetAfterDelay()
      }).class("counter-button counter-reset").children(
        h.isRunning(DelayReset) ? "Resetting" : "Reset in 1 second"
      ),
      Button(h, { onPress: CounterMessage.ClickedToggleAutoCount() })
        .class(
          "counter-button",
          model.isAutoCounting ? "counter-stop" : "counter-start"
        ).children(model.isAutoCounting ? "Stop" : "Auto-count")
    )
})
```

Click "+1", then click the Effect UI button in the bottom-right corner. [DevTools](#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.** One Model, held at the root. Message destination: A1.

1. A click in A1's view produces a Message.
2. A wraps it in a Message of its own.
3. Root wraps it again, and the runtime delivers it to the root update.
4. Root's update passes it to A's update.
5. A's update passes it to A1's update, which returns a new value.
6. A puts that value in its part of the Model.
7. Root puts A's part in the application Model.
8. The view runs from the root with the new Model.

**Effect UI.** One Model per Component. Message destination: A1.

1. A click in A1's view produces a Message.
2. The runtime delivers it to A1's update.
3. The runtime stores A1's new Model, and A1's view runs.

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

**Foldkit 0.x: Page stores and forwards for Counter**

`Counter.ts`

```ts
import { Schema } from "effect"
import type { Update } from "foldkit"
import { defineMessageUnion } from "foldkit/message"
import { defineView } from "foldkit/submodel"

export const Model = Schema.Struct({ count: Schema.Number })
export type Model = typeof Model.Type

export const Message = defineMessageUnion({
  ClickedDecrement: {},
  ClickedIncrement: {}
})
export type Message = typeof Message.Type

export const init = (): Model => ({ count: 0 })

export const update = (
  model: Model,
  message: Message
): Update.Return<Model, Message> =>
  Message.match(message, {
    ClickedDecrement: () => ({ model: { count: model.count - 1 } }),
    ClickedIncrement: () => ({ model: { count: model.count + 1 } })
  })

export type ViewInputs = Readonly<{ label: string }>

export const view = defineView<Model, Message, ViewInputs>(
  (model, viewInputs, h) =>
    h.div([h.Class("counter")], [
      h.span([h.Class("counter-label")], [viewInputs.label]),
      h.button([
        h.Class("counter-button"),
        h.AriaLabel("Decrement"),
        h.OnClick(Message.ClickedDecrement())
      ], ["-"]),
      h.output([h.Class("counter-value")], [String(model.count)]),
      h.button([
        h.Class("counter-button"),
        h.AriaLabel("Increment"),
        h.OnClick(Message.ClickedIncrement())
      ], ["+"])
    ])
)
```

`Page.ts`

```ts
import { Option, Schema } from "effect"
import { Update } from "foldkit"
import type { Html, HtmlBuilder } from "foldkit/html"
import { defineMessageUnion } from "foldkit/message"
import * as Counter from "./Counter.ts"

export const Model = Schema.Struct({
  isCounterShown: Schema.Boolean,
  counter: Counter.Model
})
export type Model = typeof Model.Type

export const Message = defineMessageUnion({
  ClickedToggleCounter: {},
  GotCounterMessage: { message: Counter.Message }
})
export type Message = typeof Message.Type

export const init = () => ({
  model: { isCounterShown: true, counter: Counter.init() }
})

// Runs Counter.update on the Counter Model stored in Page's Model
// and writes the result back.
const foldCounter = Update.foldChild({
  update: Counter.update,
  read: (model: Model) => Option.some(model.counter),
  write: (model: Model, counter: Counter.Model): Model => ({
    ...model,
    counter
  }),
  toParentMessage: (message: Counter.Message): Message =>
    Message.GotCounterMessage({ message })
})

export const update = (
  model: Model,
  message: Message
): Update.Return<Model, Message> =>
  Message.match(message, {
    ClickedToggleCounter: () => ({
      model: { ...model, isCounterShown: !model.isCounterShown }
    }),
    GotCounterMessage: ({ message }) => foldCounter(model, message)
  })

export const view = (model: Model, h: HtmlBuilder<Message>): Html =>
  h.div([h.Class("counter-page")], [
    h.button([h.OnClick(Message.ClickedToggleCounter())], [
      model.isCounterShown ? "Hide counter" : "Show counter"
    ]),
    model.isCounterShown
      ? h.submodel({
        slotId: "counter",
        model: model.counter,
        view: Counter.view,
        viewInputs: { label: "Likes" },
        toParentMessage: (message) =>
          Message.GotCounterMessage({ message })
      })
      : h.empty
  ])
```

**Effect UI: Page renders Counter**

`Counter.ts`

```ts
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("+")
    )
})
```

`Page.ts`

```ts
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" } })
    )
})
```

### 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.ts`

```ts
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(() => ({
  count: 0,
  isAutoCounting: false
}))

// 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) =>
  CounterMessage.match(message, {
    ClickedAdd: ({ amount }) =>
      $.evolve({ count: (count) => count + amount }),
    ClickedResetAfterDelay: () => $.run(DelayReset.make()),
    CompletedDelayReset: () => $.evolve({ count: 0 }),
    ClickedToggleAutoCount: () =>
      $.evolve({
        isAutoCounting: (isAutoCounting) => !isAutoCounting
      }),
    Ticked: () => $.evolve({ count: (count) => count + 1 })
  })
)

const subscriptions = CounterDef.subscriptions(({ model }) => [
  model.isAutoCounting &&
  Subscription.make(
    "tick",
    Stream.tick("1 second").pipe(
      Stream.drop(1),
      Stream.map(() => CounterMessage.Ticked())
    )
  )
])

const view = CounterDef.view((h, model) =>
  h.div.class("counter").children(
    h.output.class("counter-value").children(String(model.count)),
    Button(h, { onPress: CounterMessage.ClickedAdd({ amount: -1 }) })
      .class("counter-button counter-add")
      .children("−1"),
    Button(h, { onPress: CounterMessage.ClickedAdd({ amount: 1 }) })
      .class("counter-button counter-add")
      .children("+1"),
    Button(h, {
      props: {
        disabled: h.isRunning(DelayReset),
        focusableWhenDisabled: true
      },
      onPress: CounterMessage.ClickedResetAfterDelay()
    }).class("counter-button counter-reset").children(
      h.isRunning(DelayReset) ? "Resetting" : "Reset in 1 second"
    ),
    Button(h, { onPress: CounterMessage.ClickedToggleAutoCount() })
      .class(
        "counter-button",
        model.isAutoCounting ? "counter-stop" : "counter-start"
      ).children(model.isAutoCounting ? "Stop" : "Auto-count")
  )
)

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.ts`

```ts
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.ts`

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Schema } from "effect"
import { CartMessage, CartProvider } from "./CartProvider.ts"

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: () =>
        h.main(
          CartCount(h, {}),
          h.article(h.h3("Notebook"), AddToCart(h, {}))
        )
    })
})

const CartCount = Html.component({
  name: "CartCount",
  model: Schema.Null,
  message: Schema.Never,
  // Lists the Provider to read from.
  reads: { cart: CartProvider }
}).make({
  init: () => null,
  update: ($) => $.model,
  // h.reads.cart holds CartProvider's shared value. CartCount
  // renders again when that value changes.
  view: (h) => h.output(`${h.reads.cart.count} in cart`)
})

const AddToCartMessage = UiSchema.TaggedEnum({ ClickedAdd: {} })

const AddToCart = Html.component({
  name: "AddToCart",
  model: Schema.Null,
  message: AddToCartMessage
}).make({
  init: () => null,
  update: {
    // Sends the Message to the nearest CartProvider above. Sending
    // needs no reads entry.
    ClickedAdd: ($) =>
      $.send(CartProvider, CartMessage.RequestedAddItem())
  },
  view: (h) =>
    h.button.on("click", AddToCartMessage.ClickedAdd())
      .children("Add to cart")
})
```

**Foldkit 0.x.** The root Model holds the shared value. Changed by: A1.

1. A click in A1's view produces a Message.
2. A and Root wrap it, and the runtime delivers it to the root update.
3. Root's update passes it through A's update to A1's update.
4. A1 doesn't own the value, so its update returns an OutMessage.
5. A's update forwards the OutMessage to Root's update.
6. Root's update handles it and changes the value in the Model.
7. The view runs from the root, and Root passes the value to A's view.
8. A's view passes it on to A1's and A2's views.

**Effect UI.** A Provider's Model holds the shared value. Changed by: A1.

1. A click in A1's view produces a Message.
2. A1's update sends a Message to the Provider.
3. The Provider's update changes the value in its Model.
4. A1 and A2 read the value, so their views run again.

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

**Foldkit 0.x: The parent stores and manages the Query**

`posts.ts`

```ts
import { Effect, Schema } from "effect"
import { AsyncData, Command, type Update } from "foldkit"
import { Query } from "foldkit/experimental"
import type { Html, HtmlBuilder } from "foldkit/html"
import { defineMessageUnion } from "foldkit/message"
import { Post, PostsApi } from "../Posts.ts"

export const postsQuery = Query.define({
  name: "Posts",
  args: { search: Schema.String },
  data: Schema.Array(Post),
  error: Schema.String,
  execute: ({ search }) => PostsApi.use((api) => api.search(search))
})

export const Model = Schema.Struct({
  search: Schema.String,
  searchVersion: Schema.Number,
  posts: postsQuery.Model
})
export type Model = typeof Model.Type

export const Message = defineMessageUnion({
  UpdatedSearch: { search: Schema.String },
  CompletedDelaySearch: { version: Schema.Number },
  GotPostsMessage: { message: postsQuery.Message }
})
export type Message = typeof Message.Type

export const DelaySearch = Command.define("DelaySearch", {
  args: { version: Schema.Number },
  messages: [Message.CompletedDelaySearch],
  execute: ({ version }) =>
    Effect.sleep("300 millis").pipe(
      Effect.as(Message.CompletedDelaySearch({ version }))
    )
})

const posts = postsQuery.lift<Model, Message>({
  parentField: "posts",
  toParentMessage: (message) => Message.GotPostsMessage({ message })
})

export const init = () =>
  posts.loadIfMissing(
    { search: "", searchVersion: 0, posts: postsQuery.init() },
    { search: "" }
  )

export const update = (
  model: Model,
  message: Message
): Update.Return<Model, Message, PostsApi> =>
  Message.match(message, {
    UpdatedSearch: ({ search }) => {
      const searchVersion = model.searchVersion + 1
      return {
        model: { ...model, search, searchVersion },
        commands: [DelaySearch({ version: searchVersion })]
      }
    },
    // Only the delay that the last keystroke started fetches.
    CompletedDelaySearch: ({ version }) =>
      version === model.searchVersion
        ? posts.loadIfMissing(model, { search: model.search })
        : { model },
    GotPostsMessage: ({ message }) => posts.fold(model, message)
  })

export const view = (model: Model, h: HtmlBuilder<Message>): Html =>
  h.div([], [
    h.input([
      h.AriaLabel("Search posts"),
      h.Value(model.search),
      h.OnInput((search) => Message.UpdatedSearch({ search }))
    ]),
    AsyncData.matchData(
      postsQuery.read(model.posts, { search: model.search }),
      {
        onEmpty: () => h.p([], ["Loading posts"]),
        onFailure: () => h.p([], ["Could not load posts"]),
        onData: (posts) =>
          h.ul([], posts.map((post) => h.li([], [post.title])))
      }
    )
  ])
```

**Effect UI: The Component lists its query**

`Posts.ts`

```ts
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))
```

### 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:

| State                                                             | Stored in                 |
| ----------------------------------------------------------------- | ------------------------- |
| A Component's own state                                           | Its own Model             |
| State a parent or a [Provider](#shared-state-with-providers) owns | Another Component's Model |
| Data a [query](#data-fetching-with-queries) fetched               | The runtime's query cache |
| Which Commands are running                                        | The 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.ts`

```ts
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.ts`

```ts
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](https://base-ui.com/), 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.

Components: 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.ts`

```ts
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.ts`

```ts
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.ts`

```ts
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](#host-agnostic-rendering). 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.ts`

```ts
import { HtmlLocator, HtmlPlay } from "@effect/ui/html/testing"
import { it } from "@effect/vitest"
import { Effect } from "effect"
import { TestClock } from "effect/testing"
import { Counter } from "./Counter.ts"

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

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

An interactive figure runs this test in the browser, on the test host with a TestClock. A slider steps through it one line at a time and shows the app as the test host holds it, the TestClock and whether DelayReset is running. The test clicks +1 and Reset, so the count is 1 and DelayReset is asleep. It advances the clock to 999 ms, and the count is still 1. It advances the clock one more millisecond. DelayReset finishes, the runtime delivers CompletedDelayReset, and the count is 0.

`App.play.test.ts`

```ts
import type { Session } from "#domain/Session"
import { Router } from "@effect/ui"
import { HtmlLocator, HtmlPlay } from "@effect/ui/html/testing"
import { Locator, TestHost } from "@effect/ui/testing"
import { assert, it } from "@effect/vitest"
import { Effect, Layer, Option } from "effect"
import { KeyValueStore } from "effect/persistence"
import { TestClock } from "effect/testing"
import { App, appProps } from "./App.ts"
import { SessionStore } from "./auth/services/SessionStore.ts"
import { AppRoute } from "./routes.ts"

const alice: Session = {
  userId: "1",
  email: "alice@example.com",
  name: "alice"
}

const AppTest = (url: string) =>
  Layer.mergeAll(
    Router.memory({ routes: AppRoute, url }),
    SessionStore.layer.pipe(Layer.provide(KeyValueStore.layerMemory)),
    TestHost.layer()
  )

const storedSession = SessionStore.use((store) => store.get)

const currentUrl = Effect.map(Router.Router, (router) => router.location().url)

it.effect("a successful login saves the session and lands on the dashboard", () =>
  Effect.gen(function*() {
    const play = yield* HtmlPlay.make(App, appProps)
    yield* play.type(HtmlLocator.label("Email"), alice.email)
    yield* play.type(HtmlLocator.label("Password"), "password")
    yield* play.click(HtmlLocator.role("button", { name: "Sign In" }))
    yield* TestClock.adjust("1 second")
    yield* play.expect(Locator.text("Welcome back, alice!")).toExist()
    assert.deepStrictEqual(yield* storedSession, Option.some(alice))
    assert.strictEqual(yield* currentUrl, "/dashboard")
  }))
```

A second tab runs this test of the sign-in flow in `examples/auth`. The router and the session store keep their data in memory. The test types an email and a password, and the form enables its button. It clicks Sign In. The real sign-in Command starts a request that takes one second, and the button reads "Signing in...". It advances the clock one second. The app shows the dashboard, the session is in the store and the URL is /dashboard.

`SnakeGame.play.test.ts`

```ts
import { HtmlPlay } from "@effect/ui/html/testing"
import { Locator } from "@effect/ui/testing"
import { it } from "@effect/vitest"
import { Effect, Random } from "effect"
import { TestClock } from "effect/testing"
import { SnakeGame } from "./SnakeGame.ts"

const scored = Locator.text("Score: 10")
const paused = Locator.text("Paused - SPACE to continue")

it.effect("steers to the apple, eats it and pauses", () =>
  Effect.gen(function*() {
    // The seed below puts the first apple one row up from the snake
    // and six cells to its right. The snake moves every 150 ms.
    const play = yield* HtmlPlay.make(SnakeGame, {})
    yield* play.keydown("document", " ")
    yield* play.keydown("document", "ArrowUp")
    yield* TestClock.adjust("150 millis")
    yield* play.keydown("document", "ArrowRight")
    yield* TestClock.adjust("900 millis")
    yield* play.expect(scored).toExist()
    yield* play.keydown("document", " ")
    yield* TestClock.adjust("10 seconds")
    yield* play.expect(paused).toExist()
  }).pipe(Random.withSeed("e")))
```

A third tab runs this test of the Snake game in `examples/snake`. A seed fixes where the apple appears. The test presses Space to start the game and the up arrow to turn, then advances the TestClock 150 ms, which is one move. It presses the right arrow and advances the clock 900 ms, which is six moves. The snake reaches the apple and the score is 10. It presses Space to pause and advances the clock ten seconds, and the snake doesn't move.

## 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](https://github.com/krausest/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.

| Entry | JavaScript time, as a multiple of vanilla JavaScript |
| --- | ---: |
| Vanilla JS | 1.00× |
| Solid | 1.87× |
| Svelte | 2.41× |
| Vue | 3.75× |
| Effect UI | 4.12× |
| React | 6.44× |
| Foldkit 0.x | 6.55× |

**Median time running JavaScript per operation**

| Workload | Vanilla JS | Effect UI | React | Foldkit 0.x | Vue | Svelte | Solid |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| Create 1,000 rows | 6.9 ms | 23.3 ms | 23.6 ms | 41.6 ms | 22.9 ms | 11.5 ms | 10.1 ms |
| Replace 1,000 rows | 15.4 ms | 32.0 ms | 41.3 ms | 55.5 ms | 33.3 ms | 22.6 ms | 21.3 ms |
| Update every 10th row | 1.1 ms | 16.1 ms | 12.9 ms | 24.0 ms | 7.3 ms | 3.4 ms | 2.8 ms |
| Select a row | 0.8 ms | 6.9 ms | 8.4 ms | 10.3 ms | 3.4 ms | 7.3 ms | 2.7 ms |
| Swap two rows | 0.6 ms | 6.3 ms | 62.3 ms | 8.3 ms | 3.8 ms | 4.7 ms | 3.3 ms |
| Remove a row | 1.0 ms | 3.1 ms | 3.6 ms | 4.1 ms | 8.5 ms | 1.7 ms | 1.1 ms |
| Create 10,000 rows | 68.8 ms | 181 ms | 422 ms | 399 ms | 203 ms | 101 ms | 93.7 ms |
| Append 1,000 rows | 7.3 ms | 25.2 ms | 25.7 ms | 43.4 ms | 22.3 ms | 12.7 ms | 10.6 ms |
| Clear 1,000 rows | 30.9 ms | 40.0 ms | 64.3 ms | 57.5 ms | 46.5 ms | 36.1 ms | 40.6 ms |

**Page load and memory**

| Workload | Vanilla JS | Effect UI | React | Foldkit 0.x | Vue | Svelte | Solid |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| Compressed size | 2.5 kB | 52.8 kB | 51.4 kB | 87.0 kB | 23.3 kB | 9.7 kB | 4.5 kB |
| First paint | 64.8 ms | 381 ms | 419 ms | 691 ms | 154 ms | 106 ms | 68.2 ms |
| Memory after load | 0.6 MB | 1.2 MB | 1.2 MB | 2.3 MB | 0.9 MB | 0.7 MB | 0.6 MB |
| Memory with 1,000 rows | 1.9 MB | 4.1 MB | 4.4 MB | 6.1 MB | 3.9 MB | 2.9 MB | 2.7 MB |

## 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](https://pkg.pr.new/~/Effect-TS/ui). To install the latest one:

```sh
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](https://github.com/Effect-TS/ui#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](https://github.com/Effect-TS/ui/tree/main/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](https://github.com/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](https://github.com/Effect-TS/ui/tree/main/examples/launch) in `examples/launch` in Effect-TS/ui.
