This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendhigh PriorityID: react-hook-form-zod

React Hook Form & Zod Strict Uncontrolled Validation

High-performance form state management with React Hook Form and Zod schema validation. Eliminates per-keystroke re-render waterfalls via uncontrolled inputs, enforces type-safe resolvers, and manages loading states.

Prohibited Anti-Pattern: AI binds every form input to useState causing massive re-renders on every keystroke and loose manual validation.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Hook Form & Zod Strict Uncontrolled Validation - High-performance form state management with React Hook Form and Zod schema validation. Eliminates per-keystroke re-render waterfalls via uncontrolled inputs, enforces type-safe resolvers, and manages loading states.
globs: **/*Form*.tsx, **/components/forms/**/*.tsx
alwaysApply: false
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-hook-form-zod"
---

# React Hook Form & Zod Strict Uncontrolled Validation

> **Severity**: HIGH | **Category**: frontend
> **Anti-Pattern Warning**: AI binds every form input to useState causing massive re-renders on every keystroke and loose manual validation.

## System Constraints
You are a senior React performance engineer. Avoid building forms with useState or controlled inputs that trigger re-renders on every keystroke. Use react-hook-form with @hookform/resolvers/zod to guarantee zero unnecessary renders and full compile-time type safety.

## Strict Guidelines
- Never manage multi-field form inputs with individual useState hooks; use useForm<T>() with uncontrolled inputs.
- Bind form schemas using zodResolver(schema) to guarantee unified compile-time and runtime validation.
- Always extract isSubmitting and errors from formState to handle loading spinners and error feedback gracefully.
- Use Controller only when integrating complex third-party custom components (e.g., date pickers, rich text editors).

## Bad vs Good Implementations
### Uncontrolled useForm with Zod Resolver vs Keystroke Re-Render Waterfall

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Every keystroke triggers a full virtual DOM reconciliation cycle, causing UI lag on lower-end devices.
```tsx
// ANTI-PATTERN: useState causing re-render on every single keystroke
export function RegisterForm() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!email.includes("@")) { setError("Invalid email"); return; }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input value={email} onChange={(e) => setEmail(e.target.value)} />
      <input value={password} onChange={(e) => setPassword(e.target.value)} />
      {error && <span>{error}</span>}
      <button type="submit">Submit</button>
    </form>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Inputs remain uncontrolled with refs; zero re-renders occur during typing, and Zod validates inputs synchronously.
```tsx
// PRODUCTION STANDARD: React Hook Form + Zod Schema Resolver
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const registerSchema = z.object({
  email: z.string().email("Valid corporate email required"),
  password: z.string().min(8, "Password must be at least 8 characters"),
});

type RegisterFormData = z.infer<typeof registerSchema>;

export function RegisterForm({ onSubmit }: { onSubmit: (data: RegisterFormData) => Promise<void> }) {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <input {...register("email")} className="input-field" placeholder="[email protected]" />
        {errors.email && <p className="text-red-500 text-sm">{errors.email.message}</p>}
      </div>
      <div>
        <input {...register("password")} type="password" className="input-field" />
        {errors.password && <p className="text-red-500 text-sm">{errors.password.message}</p>}
      </div>
      <button type="submit" disabled={isSubmitting} className="btn-primary">
        {isSubmitting ? "Submitting..." : "Create Account"}
      </button>
    </form>
  );
}
```

### Controller Integration for Headless Components

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Headless components without native inputs cannot forward ref and value via standard register.
```tsx
// ANTI-PATTERN: Forcing uncontrolled register on headless selector
<HeadlessSelect {...register("category")} />
```

#### Production Standard (Correct)
> **Standard**: Controller bridges custom headless UI elements into the form state with full type safety.
```tsx
// PRODUCTION STANDARD: Clean Controller wrapper
import { Controller, useForm } from "react-hook-form";

<Controller
  control={control}
  name="category"
  render={({ field }) => (
    <HeadlessSelect value={field.value} onChange={field.onChange} />
  )}
/>
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Hook Form & Zod Strict Uncontrolled Validation

React Hook Form & Zod Strict Uncontrolled Validation defines an industrial-grade behavioral standard for frontend engineering. High-performance form state management with React Hook Form and Zod schema validation. Eliminates per-keystroke re-render waterfalls via uncontrolled inputs, enforces type-safe resolvers, and manages loading states. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI binds every form input to useState causing massive re-renders on every keystroke and loose manual validation. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI binds every form input to useState causing massive re-renders on every keystroke and loose manual validation.High
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Never manage multi-field form inputs with individual useState hooks

Never manage multi-field form inputs with individual useState hooks; use useForm<T>() with uncontrolled inputs.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Bind form schemas using zodResolver(schema) to guarantee unified compile-time and runtime validation.

Bind form schemas using zodResolver(schema) to guarantee unified compile-time and runtime validation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Always extract isSubmitting and errors from formState to handle loading spinners and error feedback gracefully.

Always extract isSubmitting and errors from formState to handle loading spinners and error feedback gracefully.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Use Controller only when integrating complex third-party custom components (e.g., date pickers, rich text editors).

Use Controller only when integrating complex third-party custom components (e.g., date pickers, rich text editors).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is React Hook Form & Zod Strict Uncontrolled Validation critical for AI coding assistants?

High-performance form state management with React Hook Form and Zod schema validation. Eliminates per-keystroke re-render waterfalls via uncontrolled inputs, enforces type-safe resolvers, and manages loading states. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI binds every form input to useState causing massive re-renders on every keystroke and loose manual validation.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

React