Why tea-effect
Most of the difficulty in a front-end application is not rendering. It is knowing where the state is, who is allowed to change it, and what happens when something goes wrong halfway through.
tea-effect answers those three questions with one architecture, taken from Elm, and one runtime, Effect.
The architecture
There is a single Model holding all state. The only way it ever changes is a Msg passing through a single update function.
┌──────────────────────────────────────────┐
│ │
▼ │
┌───────┐ view ┌──────┐ dispatch ┌──────────┐
│ Model │ ────────► │ Html │ ─────────► │ Msg │
└───────┘ └──────┘ └──────────┘
▲ │
│ update(msg, model) │
└──────────────────────────────────────────┘
│
│ returns [ Model, Cmd ]
▼
┌──────────┐
│ runtime │ runs the Cmd, feeds the
└──────────┘ resulting Msg back in
▲
┌──────────┐
│ Sub │ external events (timers, storage,
└──────────┘ the URL) enter the same wayEverything - a click, an HTTP response, a timer tick, a browser back button - arrives as a Msg and goes through the same update. There is no second path into the state, so "how did this value get here?" always has one answer.
Side effects are values, not actions
This is the part that does the real work, and it is worth being precise about.
update does not perform the work. It returns a description of the work:
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
switch (msg.type) {
case 'Roll':
// `update` does not roll the die. It returns a command that says
// "run this, and send me back a Rolled message".
return [{ ...model, rolling: true }, Task.perform(Rolled)(rollDie)]
case 'Rolled':
return [{ face: msg.face, rolling: false }, Cmd.none]
}
}The complete file, imports included
import { Effect } from 'effect'
import * as Cmd from 'tea-effect/Cmd'
import * as Task from 'tea-effect/Task'
import type * as TeaReact from 'tea-effect/React'
export type Model = {
readonly face: number
readonly rolling: boolean
}
export type Msg =
| { readonly type: 'Roll' }
| { readonly type: 'Rolled'; readonly face: number }
// #region task
// A message constructor. Keep it at module level: a stable reference is what lets
// `Html.map` cache the mapped dispatch, so memoised children below can bail out.
const Rolled = (face: number): Msg => ({ type: 'Rolled', face })
// A description of a side effect. Nothing has happened yet - this is just a value.
// `Task<A, E, R>` is an alias for Effect's own `Effect<A, E, R>`, so every Effect
// already is a Task. The annotation here is only to make that visible.
const rollDie: Task.Task<number> = Effect.sync(() => 1 + Math.floor(Math.random() * 6))
// #endregion task
export const init: readonly [Model, Cmd.Cmd<Msg>] = [{ face: 1, rolling: false }, Cmd.none]
// #region update
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
switch (msg.type) {
case 'Roll':
// `update` does not roll the die. It returns a command that says
// "run this, and send me back a Rolled message".
return [{ ...model, rolling: true }, Task.perform(Rolled)(rollDie)]
case 'Rolled':
return [{ face: msg.face, rolling: false }, Cmd.none]
}
}
// #endregion update
export const view =
(model: Model): TeaReact.Html<Msg> =>
(dispatch) => (
<div>
<span>{model.face}</span>
<button onClick={() => dispatch({ type: 'Roll' })} disabled={model.rolling}>
Roll
</button>
</div>
)Task.perform(Rolled)(rollDie) is a Cmd<Msg> - an inert value. The runtime is what eventually executes it and feeds the resulting Rolled message back into update.
Two consequences follow:
updateis a pure function. Testing it means calling it and comparing the result. No mocks, no fake timers, no test renderer.- Effects are inspectable. A
Cmdcan be mapped, batched, or passed up to a parent module before anything runs.
The same holds for subscriptions. subscriptions(model) declares which external sources should be live for this model, and the runtime diffs that against what is currently running - starting and stopping only the difference.
What Effect adds
TEA on its own says nothing about how effects run. That is where Effect comes in, and it is why this library exists rather than being a 200-line reimplementation of Redux.
A Cmd<Msg, E, R> is an Effect Stream. Those last two parameters are the point:
E | What this command can fail with - in the type, checked at compile time. The failure surfaces on the program's model stream instead of vanishing into an unhandled rejection. |
R | What services this command needs to run. A command that needs an ApiClient says so in its type, and the program will not compile until one is provided. |
On top of that you get the things Effect already solved: structured concurrency (shutting a program down interrupts its in-flight commands and closes their resources), retry and timeout policies, and Schema for validating data crossing the boundary into your app.
The Http module uses all of it:
// JSONPlaceholder is a free public test API. These requests run as they are -
// nothing below is a stand-in for a real endpoint.
const BASE_URL = 'https://jsonplaceholder.typicode.com'
// A request is a value. Building one sends nothing.
export const listUsers = pipe(
Http.get(`${BASE_URL}/users`, Http.expectJson(Schema.Array(User))),
Http.withTimeout(5000)
)
// JSONPlaceholder replies with the object you sent plus an id, but does not
// store it: the next listUsers still returns the original ten users.
export const createUser = (user: NewUser) =>
Http.post(`${BASE_URL}/users`, Http.jsonBody(NewUser, user), Http.expectJson(User))The complete file, including the User schema
import { Schema, pipe } from 'effect'
import * as Http from 'tea-effect/Http'
// #region schema
// A JSONPlaceholder user carries more than this - address, phone, company.
// Schema.Struct ignores fields you do not list, so the model stays as small as
// the application actually needs.
export const User = Schema.Struct({
id: Schema.Number,
name: Schema.String,
username: Schema.String,
email: Schema.String
})
export type User = Schema.Schema.Type<typeof User>
export const NewUser = Schema.Struct({
name: Schema.String,
username: Schema.String,
email: Schema.String
})
export type NewUser = Schema.Schema.Type<typeof NewUser>
// #endregion schema
// #region requests
// JSONPlaceholder is a free public test API. These requests run as they are -
// nothing below is a stand-in for a real endpoint.
const BASE_URL = 'https://jsonplaceholder.typicode.com'
// A request is a value. Building one sends nothing.
export const listUsers = pipe(
Http.get(`${BASE_URL}/users`, Http.expectJson(Schema.Array(User))),
Http.withTimeout(5000)
)
// JSONPlaceholder replies with the object you sent plus an id, but does not
// store it: the next listUsers still returns the original ten users.
export const createUser = (user: NewUser) =>
Http.post(`${BASE_URL}/users`, Http.jsonBody(NewUser, user), Http.expectJson(User))
// #endregion requests
// #region posts
export const Post = Schema.Struct({
id: Schema.Number,
userId: Schema.Number,
title: Schema.String
})
export type Post = Schema.Schema.Type<typeof Post>
export const postsOf = (userId: number) =>
Http.get(`${BASE_URL}/posts?userId=${userId}`, Http.expectJson(Schema.Array(Post)))
// #endregion posts
// #region headers
// JSONPlaceholder needs no authentication. This is the shape for an API that does.
// Modifiers are ordinary Request -> Request functions, so a combination you use
// everywhere can be named once and then piped in like any other modifier.
export const authorized = (token: string) => Http.withHeaders([Http.bearerToken(token)])
export const createUserAs = (token: string, user: NewUser) =>
pipe(createUser(user), authorized(token))
// #endregion headers
// #region download
// JSONPlaceholder sends no Content-Disposition, so the file is named after the
// last URL segment: this saves the user list as a file called `users`.
export const usersFile = Http.get(`${BASE_URL}/users`, Http.expectFile)
// #endregion download
// #region upload
// JSONPlaceholder accepts the upload and answers with an id, but keeps nothing.
export const Created = Schema.Struct({ id: Schema.Number })
// The whole body is the file: the server reads it as it is.
export const uploadCsv = (csv: File) => Http.post(`${BASE_URL}/posts`, Http.fileBody(csv), Http.expectJson(Created))
// A form: fields and files together, as multipart/form-data.
export const uploadAvatar = (photo: File) =>
Http.post(
`${BASE_URL}/posts`,
Http.multipartBody([Http.stringPart('userId', '1'), Http.filePart('avatar', photo)]),
Http.expectJson(Created)
)
// #endregion uploadThe response is decoded and validated against the User schema before it can reach your Model. A malformed payload becomes a typed BadBody error, not an undefined three components away from where it originated.
How it compares
| Redux / RTK | Zustand | tea-effect | |
|---|---|---|---|
| Single source of state | Yes | Per-store | Yes |
| Pure state transition | Yes (reducer) | No (mutating setters) | Yes (update) |
| Side effects | Middleware / thunks / sagas | Inside setters or components | Values returned from update |
| Effect errors | Untyped | Untyped | In the type (E) |
| Effect dependencies | Manual wiring | Manual wiring | In the type (R) |
| Cancellation | Manual | Manual | Structured, automatic |
| Boundary validation | Bring your own | Bring your own | Schema, built in |
Against elm-ts, whose design tea-effect follows directly:
| elm-ts | tea-effect | |
|---|---|---|
| Effect library | fp-ts + RxJS | Effect |
| Streaming | RxJS Observable | Effect Stream |
| Error handling | Either<E, A> | Effect<A, E, R> |
| Dependency injection | Reader pattern | Built-in R |
| Runtime validation | io-ts | Schema |
| Resource management | Manual | Scope, automatic |
What tea-effect is not
Being clear about this saves you an evaluation:
- It is not a framework. No router-driven file layout, no build tooling, no opinions about your bundler. It is a runtime plus a set of modules.
- It does not have its own virtual DOM.
viewreturns whatever your renderer understands. The React bindings are included; the core is generic. - It is not a drop-in replacement for local component state. A
useStatefor whether a tooltip is open is fine. tea-effect is for the state that features are built out of.
When you should not use it
- Your team has no appetite for learning Effect. The
E/Rtype parameters are the payoff, and they are also the learning curve. Budget for it honestly - see Getting started. - The app is a thin CRUD shell where a data-fetching library plus local state already covers everything. TEA earns its keep when state transitions get genuinely complicated, not before.
- You need a large ecosystem of ready-made integrations today. This is a young library with a small surface.
Where to go next
- Getting started - install it and build a counter.
- The mental model -
Model,Msg,Cmd,Sub, and how the loop actually runs.