Typed React Forms for Email Verification States
Email verification looks like a small form: enter an address, click send, wait for a message, then enter a code. In a real React product, that “small” feature crosses several async boundaries. The request can be slow, th
Email verification looks like a small form: enter an address, click send, wait for a message, then enter a code. In a real React product, that “small” feature crosses several async boundaries. The request can be slow, the user can click twice, the code can expire, and the browser can lose its connection at exactly the wrong moment.
The fix is not a larger spinner. It is a typed model of the states the UI already has.
Why email verification UI becomes a state machine
If a component stores isLoading, error, code, and verified as unrelated booleans, impossible combinations start appearing. A screen can become “verified” while an old error is still visible. A second request can finish before the first one and replace newer information. These bugs are easy to miss because the happy path still works.
I prefer to model the flow as one value. The value says what the user can do now, and it carries only the data that makes sense for that state. This is useful whether the address is a normal inbox or a throwaway email address used for a short-lived test account.
A small discriminated union
TypeScript gives us a compact contract for the React component:
type VerificationState =
| { kind: "idle"; email: string }
| { kind: "sending"; email: string; requestId: string }
| { kind: "codeSent"; email: string; expiresAt: string }
| { kind: "verifying"; email: string; code: string }
| { kind: "verified"; email: string }
| { kind: "error"; email: string; message: string; retryable: boolean };
Now the render logic has a useful boundary. The send button is disabled for sending, the code input appears for codeSent and verifying, and the success panel appears only for verified. There is no separate boolean to accidentally forget to reset.
The union also makes event handling clearer:
type VerificationEvent =
| { type: "editEmail"; email: string }
| { type: "sendStarted"; requestId: string }
| { type: "codeSent"; expiresAt: string }
| { type: "verifyStarted"; code: string }
| { type: "verified" }
| { type: "failed"; message: string; retryable: boolean };
A reducer can reject or ignore events that do not belong to the current state. That is a modest amount of code, but it prevents a surprising amount of UI drift.
Keep the async boundary boring
The component should not know how the API stores tokens. Put that detail behind a small client and return ordinary data:
type SendResult = { expiresAt: string };
async function requestCode(email: string): Promise<SendResult> {
const response = await fetch("/api/verification/send", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email }),
});
if (!response.ok) {
throw new Error("We could not send a verification code.");
}
return response.json() as Promise<SendResult>;
}
On the server side, the endpoint should be safe to retry. A user may refresh, a mobile browser may retry, or a test runner may submit twice. Designing an idempotent verification endpoint keeps those duplicate requests from creating confusing tokens.
In the component, assign a request ID before starting. When the response arrives, update the state only if that request is still current. An AbortController can cancel work on unmount, but it should not be your only protection: cancellation is not guaranteed once a request has reached the server.
const requestId = crypto.randomUUID();
dispatch({ type: "sendStarted", requestId });
try {
const result = await requestCode(email);
if (latestRequest.current !== requestId) return;
dispatch({ type: "codeSent", expiresAt: result.expiresAt });
} catch {
if (latestRequest.current === requestId) {
dispatch({
type: "failed",
message: "The code could not be sent. Try again in a moment.",
retryable: true,
});
}
}
That guard is a little verbose, but it makes the race visible. Future-you will thank it.
Make errors useful and accessible
An error message should explain the next action, not expose an implementation detail such as 500 from /api/verification/send. Keep the technical reason in structured logs and give the user a short recovery path.
For React, connect the message to the form with aria-live="polite" and keep focus behavior deliberate. When a code is sent, focus the first code input. When verification fails, focus the error summary or return focus to the code field. Do not move focus on every keystroke; that gets annoying pretty quick.
Also distinguish invalid input from a failed request. “Enter a valid email address” is a local validation problem. “We could not send the code” is a network or server problem. They need different copy, metrics, and retry behavior.
Test transitions instead of snapshots
Snapshot tests can tell you that markup changed. They are less useful for proving that a stale response cannot overwrite a newer one. Test the transition table instead:
- idle → sending → codeSent
- idle → sending → error
- codeSent → verifying → verified
- codeSent → verifying → error
- sending → sending, with the second action ignored or explicitly coalesced
Mock the API at the boundary and control promise resolution order. A test that resolves request B before request A is worth more here than another snapshot of the success panel. For browser-level checks, keep an evidence ledger for browser tests so a failed run records the request, visible state, and final message.
Q&A: practical edge cases
Should the code input be a separate form?
Usually yes. A separate form gives the code submission its own submit event and makes keyboard behavior easier to reason about. It also lets you disable only the action that is currently pending.
What if the code expires while the user is typing?
Treat expiration as a normal error state with a clear “Send a new code” action. Do not silently clear the code; users may think the form lost their input.
Should I accept a throwaway email address?
That is a product and abuse decision, not a frontend validation trick. If your service needs a durable contact, explain that requirement. If the flow is for testing, demos, or a low-risk trial, model the policy explicitly and measure what happens.
Where does the typo tempail mail belong?
If you need to understand search traffic or legacy user language, keep it as a plain-text synonym in internal notes or carefully written help copy. Never make an accidental-looking phrase the label for a security-sensitive action.
Final checklist
Before shipping, check that every async state has a visible outcome, duplicate submissions are safe, stale responses are ignored, and errors tell users what to do next. Verify keyboard focus and screen-reader announcements. Then test both success and denial paths with controlled network timing.
Typed state does not make email verification simple. It makes the complexity honest, which is a much better starting point for a React feature that needs to stay dependable.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.