React Email States: A Typed Fixture Contract
Email verification looks like a small React feature: render an input, submit an address, then wait for a message. In a real product, it quickly becomes a state machine. The user can submit twice, the message can arrive l
Email verification looks like a small React feature: render an input, submit an address, then wait for a message. In a real product, it quickly becomes a state machine. The user can submit twice, the message can arrive late, a test fixture can expire, or the API can return an error after the component has unmounted.
The pattern I keep reaching for is a typed UI contract. It gives the component a short list of states and makes impossible combinations harder to represent. That matters for production flows and for test fixtures, where an email inbox may behave like a burner email: useful for a short scenario, but not something the UI should trust forever.
Why email UI becomes a state problem
A boolean such as isLoading is rarely enough. The screen may need to distinguish between:
- no address has been submitted yet;
- a verification request is running;
- the app is waiting for a matching message;
- a message was found and accepted;
- the fixture expired;
- the user can retry after a temporary failure.
If these are represented by several independent booleans, combinations like isLoading: true and hasError: true become possible. The code still compiles, but the UI can show a spinner beside a stale error. It feels random to a user and is hard to reproduce in a test.
I also avoid putting provider-specific terms directly into the component. Whether a team uses a shared test inbox, a mock server, or a temporary mailbox, React should receive the same small contract. This keeps the feature focused on user feedback instead of inbox plumbing.
For a related integration concern, version invite emails across React and Node is a useful reminder that the client and server need to agree on event shape, not just endpoint names.
Define the contract before the component
Start with the events the UI actually understands. A minimal contract can look like this:
type EmailState =
| { kind: "idle" }
| { kind: "sending"; address: string }
| { kind: "waiting"; address: string; startedAt: number }
| { kind: "verified"; address: string; messageId: string }
| { kind: "expired"; address: string }
| { kind: "failed"; message: string; retryable: boolean };
type EmailEvent =
| { type: "submit"; address: string }
| { type: "sent"; startedAt: number }
| { type: "matched"; messageId: string }
| { type: "expired" }
| { type: "error"; message: string; retryable: boolean }
| { type: "reset" };
The kind field is the important bit. TypeScript can narrow each branch, so code rendering a verified state can safely use messageId. There is no need to guess whether it exists because another boolean happened to be true.
Keep the contract small. I don't put the full email body, provider response, or an access token in this state. A short message ID is enough for diagnostics, and the server can keep sensitive details outside the browser when possible.
Model the states with a discriminated union
The transition function should be boring. Boring is good here because it makes retries and fixtures easier to reason about:
function reduceEmail(state: EmailState, event: EmailEvent): EmailState {
switch (event.type) {
case "submit":
return { kind: "sending", address: event.address };
case "sent":
if (state.kind !== "sending") return state;
return { kind: "waiting", address: state.address, startedAt: event.startedAt };
case "matched":
if (state.kind !== "waiting") return state;
return { kind: "verified", address: state.address, messageId: event.messageId };
case "expired":
if (state.kind !== "waiting") return state;
return { kind: "expired", address: state.address };
case "error":
return { kind: "failed", message: event.message, retryable: event.retryable };
case "reset":
return { kind: "idle" };
}
}
Notice that a late matched event is ignored unless the screen is waiting. This is a small guard, but it prevents an old polling request from verifying a newer attempt. At the API boundary, idempotent email verification APIs add the server-side version of the same idea.
Build a small React hook
The hook can own the reducer while the component only renders the state. A production implementation would add an AbortController and clear its timer in the effect cleanup:
function useEmailVerification() {
const [state, dispatch] = useReducer(reduceEmail, { kind: "idle" });
const submit = async (address: string) => {
dispatch({ type: "submit", address });
try {
await api.startVerification(address);
dispatch({ type: "sent", startedAt: Date.now() });
} catch {
dispatch({ type: "error", message: "Could not start verification", retryable: true });
}
};
return { state, submit };
}
The example leaves polling out on purpose. Polling belongs behind a small adapter that emits matched, expired, or error; it should not leak timer details into every button and status label. Also, spellings like tamp mail com or fake e mail com may appear in search-driven test input, but they are not valid states or validation rules by themselves.
Test transitions instead of screenshots
Reducer tests are quick and tell you more than a large screenshot suite. Cover the happy path, a duplicate event, expiry, and a retryable failure:
it("ignores a late match after expiry", () => {
let state: EmailState = { kind: "waiting", address: "[email protected]", startedAt: 1 };
state = reduceEmail(state, { type: "expired" });
state = reduceEmail(state, { type: "matched", messageId: "old-1" });
expect(state.kind).toBe("expired");
});
This style also makes fixtures clearer. A fake inbox can emit a deterministic sequence without pretending to be a browser. The test says what happened and what the UI should show, which is much easier to debug when CI is busy.
Q&A: practical tradeoffs
Should every email flow use a state machine?
No. A one-shot βsend againβ form may be fine with local state. Use an explicit union when there are asynchronous steps, retries, expiry, or more than one source of events.
Should the UI poll the inbox directly?
Usually no. Keep provider credentials and matching rules on the server or in a test adapter. The browser needs a safe status event, not the full mailbox.
What if the backend already has a state machine?
Share event names and IDs where practical, but don't force the frontend to mirror every backend state. Translate server responses into the smaller set of states the user can act on.
A shipping checklist
Before merging an email verification screen, check that:
- Every visible state has one
kindvalue. - Late events cannot update a newer attempt.
- Retry and expiry are explicit, not inferred from a timeout alone.
- Timers and requests are cleaned up on unmount.
- Tests cover transitions, not only the happy screenshot.
- Test inbox details stay out of browser state and logs.
Typed contracts are not ceremony for its own sake. They give React a stable boundary around an unreliable async workflow, so the feature is easier to ship, easier to test, and less confusing when email arrives a little late.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.