State machines7 min read
Separating State Transitions from Side Effects
Why a transition function should return effects as data — and how that makes complex flows testable, replayable and framework-agnostic.
Most bugs in complex UI flows aren't in the happy path. They live in the gaps: a wallet approval that arrives after the user clicked "cancel", a retry that fires while a request is still in flight, a chain switch that half-succeeds. The root cause is usually the same — deciding what should happen and making it happen are tangled together.
This article is about pulling them apart.
The tangled version
Here's a typical connect handler. It reads fine, which is exactly the problem:
async function connect() {
setStatus("connecting");
try {
const [account] = await provider.request({ method: "eth_requestAccounts" });
setAccount(account);
localStorage.setItem("session", account);
setStatus("connected");
} catch (error) {
setError(error);
setStatus("error");
toast.error("Connection failed");
}
}Questions this code can't answer:
- What happens if
connect()is called twice? - Can the user disconnect while
connecting? What resolves first? - How many retries are allowed, and where is that enforced?
- How do you test the error branch without mocking a provider,
localStorageand a toast library?
The policy (what's allowed when) is implicit, scattered across await points and setState calls.
Model the decisions
A finite state machine makes the policy explicit. States are the situations the flow can be in; events are what can happen; transitions say which events are legal in which states.
const machine = setup({ /* … */ }).createMachine({
initial: "disconnected",
states: {
disconnected: { on: { CONNECT: "connecting" } },
connecting: {
on: {
APPROVE: { target: "connected", actions: "storeAccount" },
REJECT: { target: "error", actions: "storeError" },
},
},
error: {
on: { RETRY: { target: "connecting", guard: "canRetry" } },
},
connected: { on: { DISCONNECT: "disconnected" } },
},
});Calling CONNECT twice is now a non-question: there is no CONNECT edge out of connecting. Retry policy is one named guard. Illegal combinations are not handled — they're unrepresentable.
Effects as data
The machine above still needs to do things: open the wallet prompt, persist a session, notify the user. The tempting move is to call those functions inside actions. Don't. Emit them instead:
actions: {
requestAccounts: emit({ type: "effect", effect: { kind: "requestAccounts" } }),
persistSession: emit(({ context }) => ({
type: "effect",
effect: { kind: "persistSession", account: context.account },
})),
}The machine now returns a description of the work — and whoever runs it decides how:
actor.on("effect", ({ effect }) => {
switch (effect.kind) {
case "requestAccounts":
return provider.request({ method: "eth_requestAccounts" }).then(
([account]) => actor.send({ type: "APPROVE", account }),
(error) => actor.send({ type: "REJECT", reason: error.message }),
);
case "persistSession":
return storage.set("session", effect.account);
}
});This is the functional core, imperative shell idea applied to UI flows. The core is deterministic. The shell is boring.
What you get
Tests without mocks
const effects: Effect[] = [];
const actor = createActor(walletMachine);
actor.on("effect", (e) => effects.push(e.effect));
actor.start();
actor.send({ type: "CONNECT" });
actor.send({ type: "APPROVE", account: "0xabc" });
expect(actor.getSnapshot().value).toBe("connected");
expect(effects.map((e) => e.kind)).toEqual(["requestAccounts", "persistSession"]);No provider, no storage, no DOM. The test reads like the spec.
Portability
The same machine runs under React, Vue, a CLI or a worker. Only the shell changes. This is how a wallet manager can be framework-agnostic without being lowest-common-denominator.
Replayability
Because transitions are pure, an event log is a reproduction. Feed the same events in and you get the same states and the same effects — invaluable for bug reports.
Diagrams that can't drift
The definition is data, so tooling can read it. The State Machine Visualizer draws its graph from the machine config itself.
When not to bother
A toggle doesn't need a state machine. Reach for one when a flow has more than a few states, asynchronous steps, or rules about what's allowed when — authentication, payments, wallet connections, multi-step forms, stream lifecycles.