Zod 25 🛡️ React 19 useActionState — Wiring Zod Errors into Form State with zod-form-action
The previous chapter showed the manual pattern: safeParse at the top of a Server Action, z.flattenError() to shape the errors, and a state type that the client reads. That pattern works, but it is repeated in every action, and the repetition is where subtle bugs live—mismatched state shapes, forgotten try/catch around thrown errors, inconsistent field-error typing across actions. zod-form-action is a small package that extracts the boilerplate into a single typed function, and this chapter covers what it replaces, how it works, and when the manual pattern is still the right choice.
Key point: zod-form-action wraps a Zod schema and an action body into a useActionState-compatible function, returning a discriminated union state (idle | invalid | error | success) with typed field errors, so the action body contains only domain logic and the client reads fieldError(state, "email") instead of navigating a flattened error object.
a. The boilerplate it replaces
The manual pattern from the previous chapter requires four steps in every action: convert FormData to an object, safeParse it, flatten the error, and catch any thrown errors from the domain logic. The zod-form-action README describes the repetition precisely: “It’s not hard, it’s just repetitive — and easy to get subtly wrong (mismatched state shapes, forgetting to catch a thrown error, inconsistent field-error typing)” .
// The manual pattern, repeated in every action
"use server";
export async function subscribe(prevState: State, formData: FormData) {
const raw = Object.fromEntries(formData.entries());
const parsed = schema.safeParse(raw);
if (!parsed.success) {
return { status: "invalid", errors: parsed.error.flatten().fieldErrors };
}
// ...domain logic, plus a try/catch for thrown errors
}
The package turns this into one function call. The action body receives the parsed, typed data and returns a success value; the package handles the safeParse, the error flattening, and the thrown-error catching.
import { zodAction } from "zod-form-action";
export const subscribe = zodAction(schema, async (data) => {
await db.subscribers.create(data); // data is typed and validated
return { status: "success", data };
});
The status in the return value is part of the package’s discriminated union, not a string the action invents. The package constructs the "invalid" status when validation fails and an "error" status when the action throws .
b. The state union and the client API
zod-form-action returns a state with a status discriminant: "idle", "invalid", "error", or "success" . TypeScript narrows automatically: state.errors exists only when status === "invalid", and state.data exists only when status === "success". This is the type safety the manual pattern requires the developer to maintain by hand.
The client uses initialActionState as the useActionState initial value and fieldError(state, "field") to read a field’s first error message. The hook returns the same three-tuple as the manual pattern: state, form action, and pending flag.
"use client";
import { useActionState } from "react";
import { initialActionState, fieldError } from "zod-form-action";
import { subscribe } from "./actions";
export function SubscribeForm() {
const [state, action, pending] = useActionState(subscribe, initialActionState);
return (
<form action={action}>
<input name="email" />
{fieldError(state, "email") && (
<p role="alert">{fieldError(state, "email")}</p>
)}
<button disabled={pending}>Subscribe</button>
</form>
);
}
The fieldError helper reads from state.errors only when the state is the "invalid" branch, so the client code does not need a conditional before accessing the field name .
c. React Hook Form integration and the manual fallback
The package documents two ways to combine it with React Hook Form for client-side validation UX. The recommended option uses React Hook Form’s built-in errors prop (available since v7.49.0), which reactively syncs whenever the object passed to it changes, with no useEffect needed . The mode: "onBlur" setting is required because onSubmit will not react to the errors prop.
const form = useForm({
resolver: zodResolver(schema),
errors: state.status === "invalid"
? Object.fromEntries(
Object.entries(state.errors).map(([field, msgs]) => [
field, { type: "server", message: msgs[0] },
])
)
: undefined,
mode: "onBlur", // required
});
The package is not the only option. The manual pattern from the previous chapter is still correct when the application needs full control over the state shape, when the action has multiple success variants that do not fit the "success" branch, or when adding a dependency is not desirable. The zod-form-action package has zero runtime dependencies and is MIT licensed , but the decision to adopt it is the same as any abstraction: it trades a small dependency for less repeated code.
The package’s zodAction is structurally typed against the schema’s safeParse method, so it works with any validator that exposes safeParse, not only Zod . This matters for teams migrating from Zod to another Standard Schema validator, or for codebases that already use a different library.
Complete Example Session
// ============================================
// PART 1: THE SCHEMA
// ============================================
import { z } from "zod";
const SignupSchema = z.object({
name: z.string().min(2, "Name must be at least 2 characters."),
email: z.email("Enter a valid email address."),
password: z.string().min(8, "Password must be at least 8 characters."),
});
// ============================================
// PART 2: THE ACTION (NO BOILERPLATE)
// ============================================
"use server";
import { zodAction } from "zod-form-action";
export const signup = zodAction(SignupSchema, async (data) => {
// data is typed as { name: string; email: string; password: string }
const user = await createUser(data);
return { status: "success", data: user };
});
// ============================================
// PART 3: THE CLIENT
// ============================================
"use client";
import { useActionState } from "react";
import { initialActionState, fieldError } from "zod-form-action";
import { signup } from "./actions";
export function SignupForm() {
const [state, action, pending] = useActionState(signup, initialActionState);
return (
<form action={action}>
<label htmlFor="email">Email</label>
<input id="email" name="email" disabled={pending} />
{fieldError(state, "email") && (
<p role="alert">{fieldError(state, "email")}</p>
)}
{/* ... */}
<button disabled={pending}>
{pending ? "Signing up…" : "Sign up"}
</button>
</form>
);
}
// ============================================
// PART 4: THE STATE UNION
// ============================================
// status: "idle" → initial, no errors
// status: "invalid" → validation failed, state.errors populated
// status: "error" → action threw, state.message populated
// status: "success" → action succeeded, state.data populated
The parts covered the schema, the boilerplate-free action, the client with fieldError, and the discriminated union that makes the state narrowing automatic.
Quick Reference
Package API
| Export | Purpose |
|---|---|
zodAction(schema, fn) | Wraps schema and action body |
initialActionState | Initial state for useActionState |
fieldError(state, "field") | Reads first field error |
State Union
| Status | errors | data | message |
|---|---|---|---|
"idle" | No | No | No |
"invalid" | Yes | No | No |
"error" | No | No | Yes |
"success" | No | Yes | No |
Manual vs Package
| Aspect | Manual | zod-form-action |
|---|---|---|
| Boilerplate | Repeated per action | Extracted |
| State shape | Developer-defined | Discriminated union |
| Thrown errors | Manual try/catch | Caught by package |
| Dependencies | None | One (zero runtime deps) |
| Control | Full | Constrained by union |
Best Practices
✅ Do This:
// Use the package when the boilerplate is the problem
export const action = zodAction(schema, async (data) => { ... }); // ✅
// Use initialActionState for the hook
useActionState(action, initialActionState); // ✅
// Use fieldError for display
{fieldError(state, "email") && <p>{fieldError(state, "email")}</p>} // ✅
// Use mode: "onBlur" with RHF errors prop
useForm({ errors: serverErrors, mode: "onBlur" }); // ✅
❌ Don’t Do This:
// Access state.errors without narrowing
state.errors.email; // not present on all branches // ❌
// Use mode: "onSubmit" with the RHF errors prop
useForm({ errors: serverErrors, mode: "onSubmit" }); // ❌
// Return a custom status the package does not know
return { status: "partial" }; // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
state.errors inaccessible | Accessed without narrowing | Check state.status === "invalid" |
| RHF errors not syncing | mode: "onSubmit" | Use mode: "onBlur" |
| Action throws unhandled | Not wrapped by package? | Package catches; check version |
| State shape mismatch | Custom return shape | Use the package’s union |
Real-World Examples
1. Boilerplate-free action
export const subscribe = zodAction(schema, async (data) => {
return { status: "success", data: await db.create(data) };
});
2. Client field error
{fieldError(state, "email") && <p>{fieldError(state, "email")}</p>}
3. Initial state
useActionState(action, initialActionState);
4. RHF sync
errors: state.status === "invalid" ? mapErrors(state.errors) : undefined;
5. Non-Zod validator
// Works with any validator that exposes safeParse
zodAction(customValidator, async (data) => { ... });
6. Success branch
{state.status === "success" && <p>Created: {state.data.id}</p>}
7. Error branch
{state.status === "error" && <p>{state.message}</p>}
8. Pending flag
<button disabled={pending}>{pending ? "Saving…" : "Save"}</button>
9. Multi-field form
const schema = z.object({ email: z.email(), password: z.string().min(8) });
10. Package install
npm install zod-form-action
Visual
The Boilerplate Extraction
┌─────────────────────────────────────────────────────────┐
│ MANUAL (every action) │
│ ┌──────────────────────────────────────────┐ │
│ │ Object.fromEntries(formData) │ │
│ │ schema.safeParse(raw) │ │
│ │ if (!success) flatten().fieldErrors │ │
│ │ try { domainLogic } catch { ... } │ │
│ │ return { status, errors, data } │ │
│ └──────────────────────────────────────────┘ │
│ │
│ PACKAGE │
│ ┌──────────────────────────────────────────┐ │
│ │ zodAction(schema, async (data) => { │ │
│ │ return { status: "success", data }; │ │
│ │ }) │ │
│ └──────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
The State Union
┌─────────────────────────────────────────────────────────┐
│ status: "idle" │
│ → no errors, no data │
│ │
│ status: "invalid" │
│ → state.errors.fieldName[0] │
│ │
│ status: "error" │
│ → state.message (thrown error caught) │
│ │
│ status: "success" │
│ → state.data (typed action return) │
│ │
│ TypeScript narrows on state.status │
└─────────────────────────────────────────────────────────┘
RHF Sync Flow
┌─────────────────────────────────────────────────────────┐
│ useActionState → state │
│ │ │
│ ▼ │
│ state.status === "invalid" │
│ │ │
│ ▼ │
│ map state.errors → RHF FieldErrors │
│ │ │
│ ▼ │
│ useForm({ errors: serverErrors, mode: "onBlur" }) │
│ │ │
│ ▼ │
│ RHF displays server errors in its own error state │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Package | zod-form-action |
| Main export | zodAction(schema, fn) |
| Client exports | initialActionState, fieldError |
| State union | "idle" | "invalid" | "error" | "success" |
| Runtime deps | Zero |
| Validator support | Any safeParse-compatible |
| RHF sync | errors prop with mode: "onBlur" |
| Manual pattern | Still valid for custom state shapes |
Key takeaways:
zod-form-actionextracts thesafeParse→flatten→catchboilerplate into one function call. The action body contains only the domain logic, and the package constructs the state shape .- The state is a discriminated union.
state.errorsexists only on"invalid",state.dataonly on"success", andstate.messageonly on"error". TypeScript narrows automatically, which is the type safety the manual pattern requires the developer to maintain . - The client uses
fieldError(state, "field"). The helper reads the first error for a field, so the JSX does not navigate the flattened object. - React Hook Form integration uses the
errorsprop. Withmode: "onBlur", the server errors sync into RHF’s error state withoutuseEffect. - The manual pattern is still correct when the state shape needs to be custom. The package constrains the return to its union; an action with multiple success variants or a custom error shape is better served by the hand-written pattern from the previous chapter.
Remember: The package does not do anything the manual pattern cannot do; it removes the repetition and the opportunity for subtle inconsistencies. If every action in the codebase has the same safeParse → flatten → catch sequence, the package is a smaller surface to maintain than the copied blocks. If the actions have divergent state shapes, the manual pattern is the clearer choice. The decision is the same as any abstraction: adopt it when the pattern is stable and repeated, and keep the manual form when the requirements are not uniform.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!