The mental model
If you internalise one page of this documentation, make it this one. Almost every question about tea-effect - "where do I put this?", "why is my timer restarting?", "how do I test this?" - has an answer that follows from the loop below.
The loop
- The runtime holds the current
Model. - Something produces a
Msg: a click callingdispatch, a command finishing, a subscription firing. - The runtime calls
update(msg, model), which returns[nextModel, cmd]. - The runtime stores
nextModel, hands it to the renderer, and startscmd. - When
cmdproduces a message, go to step 3.
That is the whole runtime. There is no other way for the model to change.
Model: one place for state
Model is a single value describing everything the application needs to know right now.
The useful discipline is to make illegal states unrepresentable. Rather than:
type Model = {
loading: boolean
users: ReadonlyArray<User>
error: string | null
}which permits loading: true with an error set and users present, prefer a union that only allows the states that actually exist:
export type Model =
| { readonly _tag: 'Idle' }
| { readonly _tag: 'Loading' }
| { readonly _tag: 'Loaded'; readonly users: ReadonlyArray<User> }
| { readonly _tag: 'Failed'; readonly error: Http.HttpError }Now the view cannot render a spinner and an error at the same time, because that state cannot be constructed. That is the model from the HTTP guide's example, not an illustration.
Msg: something that happened
A common mistake is writing messages as instructions - SaveUser, ShowModal. Prefer messages that describe facts:
SaveButtonClicked, notSaveUserUsersReceived, notSetUsersRequestFailed, notShowError
The difference matters because update is the only place that decides what a fact means. If the message already contains the decision, that logic has leaked into the view, and you have two places where state changes are reasoned about.
update: a pure function
(msg: Msg, model: Model) => readonly [Model, Cmd<Msg>]It does not fetch, does not read the clock, does not touch localStorage. It takes two values and returns two values.
This is what makes testing trivial:
const [next] = update({ type: 'Increment' }, { count: 0 })
expect(next).toEqual({ count: 1 })No renderer, no mocks, no async.
Cmd: a description of a side effect
A Cmd<Msg, E, R> is an inert value describing work that, once run, will produce messages. update returns one; the runtime runs it.
Here is a die roll. First the task itself - still nothing has happened:
// 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))Task and Effect are the same type
Task<A, E, R> is an alias for Effect's Effect<A, E, R> - not a wrapper, not a conversion. The name exists because Elm calls this "a task", and tea-effect keeps Elm's vocabulary where it helps.
That is why there is no Task.sync: you build tasks with Effect's own constructors, and with anything else in the Effect ecosystem. The Task module adds what Elm has and Effect does not - the conversions into Cmd (perform, attempt, attemptWith) - plus Elm-named aliases for a few combinators you already know.
And update returning it:
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]
}
}Read the Roll branch carefully. It does two things: it records that a roll is in progress, and it hands the runtime a command. The random number does not exist yet. It arrives later, as a Rolled message, and goes through update like everything else.
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>
)The constructors you will use most:
Cmd.none | Do nothing. |
Cmd.of(msg) | Produce msg without doing any work. Like any command's message, it is applied after the current dispatch returns. |
Cmd.fromEffect(effect) | Turn any Effect producing a message into a command. |
Task.perform(f)(task) | Run a task that cannot fail, map its result to a message. |
Task.attemptWith({ onSuccess, onFailure })(task) | Run a task that can fail, map both outcomes to messages. |
Cmd.batch([a, b]) | Run several commands concurrently. |
Cmd.latest(key)(cmd) | Run a command that replaces the one still running under key, so a late answer cannot overwrite a newer one. See HTTP. |
Batched commands have no ordering guarantee
Cmd.batch merges its commands with unbounded concurrency, and their messages arrive in whatever order they finish. This matches Elm. If B must happen after A, express it in update: handle A's result message and return B's command from there.
Sub: external events, declared
Commands are one-shot. Subscriptions are ongoing sources - timers, storage events, URL changes, sockets.
subscriptions is a function of the model, and this is the important part: you do not start or stop anything. You declare what should be live right now, and the runtime works out the difference.
const Tick: Msg = { type: 'Tick' }
// Declarative: describe which sources should be live for THIS model, and the
// runtime works out the difference. A `Tick` changing `seconds` re-runs this
// function, but the interval's key is unchanged, so the same timer keeps
// running - it is not reset. Flipping `running` IS the delta: off interrupts
// the interval, on starts a fresh one.
export const subscriptions = (model: Model): Sub.Sub<Msg> =>
model.running ? Sub.interval(1000, Tick) : Sub.noneEvery time the model changes, the runtime compares the subscriptions you just declared against the ones currently running, keyed by a stable identity. A subscription that was there before and is there now keeps running untouched - its timer is not reset, its DOM listener is not re-registered. Only the delta is started or stopped.
This is why Sub.interval(1000, Tick) survives unrelated model changes: the key is derived from the interval and the message, so it stays the same.
The complete file, imports included
import * as Cmd from 'tea-effect/Cmd'
import * as Sub from 'tea-effect/Sub'
import type * as TeaReact from 'tea-effect/React'
export type Model = {
readonly seconds: number
readonly running: boolean
}
export type Msg =
| { readonly type: 'Tick' }
| { readonly type: 'Toggle' }
| { readonly type: 'Reset' }
export const init: readonly [Model, Cmd.Cmd<Msg>] = [
{ seconds: 0, running: false },
Cmd.none
]
export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
switch (msg.type) {
case 'Tick':
return [{ ...model, seconds: model.seconds + 1 }, Cmd.none]
case 'Toggle':
return [{ ...model, running: !model.running }, Cmd.none]
case 'Reset':
return [{ ...model, seconds: 0 }, Cmd.none]
}
}
// #region subscriptions
const Tick: Msg = { type: 'Tick' }
// Declarative: describe which sources should be live for THIS model, and the
// runtime works out the difference. A `Tick` changing `seconds` re-runs this
// function, but the interval's key is unchanged, so the same timer keeps
// running - it is not reset. Flipping `running` IS the delta: off interrupts
// the interval, on starts a fresh one.
export const subscriptions = (model: Model): Sub.Sub<Msg> =>
model.running ? Sub.interval(1000, Tick) : Sub.none
// #endregion subscriptions
export const view =
(model: Model): TeaReact.Html<Msg> =>
(dispatch) => (
<div>
<span>{model.seconds}s</span>
<button onClick={() => dispatch({ type: 'Toggle' })}>
{model.running ? 'Stop' : 'Start'}
</button>
<button onClick={() => dispatch({ type: 'Reset' })}>Reset</button>
</div>
)Custom sources need a key
Sub.fromCallback(register) without a key argument gets a fallback identity tied to the stream object. Since subscriptions(model) typically builds a fresh stream on each call, that means teardown and re-registration on every model change. Pass a stable key - Sub.fromCallback(register, 'my-socket') - or wrap an existing stream with Sub.withKey.
How a message actually reaches update
Worth knowing, because it explains behaviour you would otherwise find surprising.
dispatch is synchronous. When your click handler calls dispatch, update runs and the renderer is called before dispatch returns, inside the same DOM event. The command update returned is started there too, after the renderer.
This is deliberate. A renderer driving controlled inputs cannot afford a delay: if the model arrived one tick late, the browser would already hold the newly typed character while the view still carried the previous value, and the reconciler would write the stale value back - moving the caret and clearing the field's native undo history.
A dispatch made while a message is being applied waits its turn. A listener, update itself, or a model$ consumer that receives its value inside dispatch may call dispatch. That message is queued and applied right after the current one, still before the outer dispatch returns. Every listener sees the models in the order they were produced.
Messages from commands and subscriptions are serialized. They arrive on fibers, so they pass through an internal queue first, and the queue guarantees they are applied one at a time and never interleave. It is not a batching or debouncing layer, but it is a fiber hop. When the fiber reading the queue is waiting, Effect's scheduler resumes it on a macrotask - setTimeout(0) in browsers, setImmediate in Node - so a command's message is applied at least one macrotask after the dispatch that returned the command, never inside it. A program built inside Effect.runSync keeps that call's microtask scheduler instead: its command messages are still applied after dispatch returns, but without waiting for a macrotask. A message that arrives while that fiber is still applying an earlier one - for example from a Cmd.of returned for a command's message - can be applied right after it, in the same macrotask. Once taken off the queue it goes through the same synchronous path a dispatch from the view takes.
Two ways to observe the model. Program.subscribe(listener) is the synchronous path described above, and it is what React.run and Html.runWith render through. Program.model$ is an Effect Stream carrying the same values, consumed on a fiber. A value can reach that fiber inside dispatch, even before the subscribe listeners run, or after dispatch returns. Which one depends on what the fiber is doing at the time, so do not rely on either. Platform.run, Platform.runWith and Html.run are built on model$ and behave the same way. Use model$ for logging, devtools, or anything that composes with other streams; use subscribe for rendering.
makeUseProgram is not on the synchronous path
The React hook pushes the model into React state from model$, not from subscribe, so it has the same timing: the state update may happen inside dispatch or after it returns. For controlled text inputs a late update is exactly the delay described above - mount through React.run until the hook moves over.
Where errors go
Cmd and Sub carry Effect's error type E. When a command, a subscription, or update itself fails, the failure surfaces on the program's model$ stream rather than disappearing into an unobserved fiber.
Two distinct concepts, easy to confuse:
- Expected failures belong in your
Msg. An HTTP 404 is not a program crash; it is aRequestFailedmessage thatupdatehandles and stores in the model. This is whatTask.attemptWithandHttp.sendare for, and it is why their commands haveE = never. Eis for the genuinely exceptional - the failure you did not model and that should tear the program down.
If you find yourself with a non-never E, ask whether that failure is really unexpected, or whether it deserves a message.
Composition
Modules compose by mapping messages. A parent embeds a child's model, and wraps the child's messages in one of its own:
Cmd.map(f)- re-label a child's commandsSub.map(f)- re-label a child's subscriptionsHtml.map(f)- re-label a child's view
Keep the tagger stable
Html.map(f) caches the mapped dispatch per (f, dispatch) pair, so a memoised child can actually bail out of re-rendering. An inline arrow - Html.map((m) => ({ type: 'Child', m })) written in the view - is a new function on every render, a new cache key, and silently defeats it. Define the tagger once at module level.
Summary
| Concept | Is | Is not |
|---|---|---|
Model | All the state, one value | Scattered across components |
Msg | A fact that happened | An instruction |
update | A pure function | A place to do I/O |
Cmd | A description of one-shot work | The work itself |
Sub | A declaration of what should be live | Something you start and stop |
Next
- Why tea-effect - if you skipped it, the trade-offs are there.
- The Getting started counter, revisited: try adding the die roll to it.