Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
React Hook Form Advanced Patterns Guide

React Hook Form Advanced Patterns Guide

Master advanced form handling with React Hook Form. Learn complex validation with Zod, dynamic fields, multi-step forms, file uploads, and server-side validation with Next.js.

react-hook-formformsvalidationzodtypescriptnextjsreact
by AntigravityAI
⭐0Stars
👁️6Views
.antigravity
# React Hook Form Advanced Patterns

Build performant, type-safe forms with React Hook Form featuring Zod validation, dynamic fields, multi-step wizards, and server integration.

## Basic Setup with Zod

### Form Configuration

```typescript
// lib/form-utils.ts
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

export const userSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  email: z.string().email("Invalid email address"),
  password: z
    .string()
    .min(8, "Password must be at least 8 characters")
    .regex(/[A-Z]/, "Password must contain an uppercase letter")
    .regex(/[0-9]/, "Password must contain a number"),
  confirmPassword: z.string(),
  role: z.enum(["user", "admin", "moderator"]),
  bio: z.string().max(500).optional(),
  website: z.string().url().optional().or(z.literal("")),
  notifications: z.object({
    email: z.boolean(),
    push: z.boolean(),
    sms: z.boolean(),
  }),
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords don't match",
  path: ["confirmPassword"],
});

export type UserFormData = z.infer<typeof userSchema>;
```

### Type-Safe Form Component

```typescript
// components/UserForm.tsx
"use client";

import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { userSchema, type UserFormData } from "@/lib/form-utils";

export function UserForm({ onSubmit }: { onSubmit: (data: UserFormData) => Promise<void> }) {
  const methods = useForm<UserFormData>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      name: "",
      email: "",
      password: "",
      confirmPassword: "",
      role: "user",
      notifications: {
        email: true,
        push: false,
        sms: false,
      },
    },
    mode: "onBlur",
  });

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting, isDirty },
    reset,
    setError,
  } = methods;

  const handleFormSubmit = async (data: UserFormData) => {
    try {
      await onSubmit(data);
      reset();
    } catch (error) {
      if (error instanceof Error) {
        setError("root", { message: error.message });
      }
    }
  };

  return (
    <FormProvider {...methods}>
      <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
        <div>
          <label htmlFor="name" className="block text-sm font-medium">
            Name
          </label>
          <input
            {...register("name")}
            id="name"
            className="mt-1 block w-full rounded-md border px-3 py-2"
          />
          {errors.name && (
            <p className="mt-1 text-sm text-red-600">{errors.name.message}</p>
          )}
        </div>

        <div>
          <label htmlFor="email" className="block text-sm font-medium">
            Email
          </label>
          <input
            {...register("email")}
            id="email"
            type="email"
            className="mt-1 block w-full rounded-md border px-3 py-2"
          />
          {errors.email && (
            <p className="mt-1 text-sm text-red-600">{errors.email.message}</p>
          )}
        </div>

        {errors.root && (
          <div className="rounded-md bg-red-50 p-4">
            <p className="text-sm text-red-800">{errors.root.message}</p>
          </div>
        )}

        <button
          type="submit"
          disabled={isSubmitting || !isDirty}
          className="w-full rounded-md bg-blue-600 py-2 text-white disabled:opacity-50"
        >
          {isSubmitting ? "Submitting..." : "Submit"}
        </button>
      </form>
    </FormProvider>
  );
}
```

## Dynamic Field Arrays

### Repeatable Fields

```typescript
// components/DynamicForm.tsx
"use client";

import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const teamSchema = z.object({
  teamName: z.string().min(1, "Team name is required"),
  members: z.array(
    z.object({
      name: z.string().min(1, "Name is required"),
      email: z.string().email("Invalid email"),
      role: z.enum(["developer", "designer", "manager"]),
    })
  ).min(1, "At least one member is required"),
});

type TeamFormData = z.infer<typeof teamSchema>;

export function TeamForm() {
  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<TeamFormData>({
    resolver: zodResolver(teamSchema),
    defaultValues: {
      teamName: "",
      members: [{ name: "", email: "", role: "developer" }],
    },
  });

  const { fields, append, remove, move } = useFieldArray({
    control,
    name: "members",
  });

  return (
    <form onSubmit={handleSubmit(console.log)} className="space-y-6">
      <input {...register("teamName")} placeholder="Team Name" />

      <div className="space-y-4">
        {fields.map((field, index) => (
          <div key={field.id} className="flex gap-4 items-start">
            <div className="flex-1">
              <input
                {...register(`members.${index}.name`)}
                placeholder="Name"
                className="w-full border rounded px-3 py-2"
              />
              {errors.members?.[index]?.name && (
                <p className="text-red-500 text-sm">
                  {errors.members[index]?.name?.message}
                </p>
              )}
            </div>

            <div className="flex-1">
              <input
                {...register(`members.${index}.email`)}
                placeholder="Email"
                className="w-full border rounded px-3 py-2"
              />
            </div>

            <select {...register(`members.${index}.role`)}>
              <option value="developer">Developer</option>
              <option value="designer">Designer</option>
              <option value="manager">Manager</option>
            </select>

            <button
              type="button"
              onClick={() => remove(index)}
              disabled={fields.length === 1}
              className="text-red-500"
            >
              Remove
            </button>
          </div>
        ))}
      </div>

      <button
        type="button"
        onClick={() => append({ name: "", email: "", role: "developer" })}
        className="text-blue-600"
      >
        + Add Member
      </button>

      <button type="submit" className="w-full bg-blue-600 text-white py-2 rounded">
        Save Team
      </button>
    </form>
  );
}
```

## Multi-Step Form Wizard

```typescript
// components/MultiStepForm.tsx
"use client";

import { useState } from "react";
import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const stepSchemas = {
  personal: z.object({
    firstName: z.string().min(1),
    lastName: z.string().min(1),
    email: z.string().email(),
  }),
  address: z.object({
    street: z.string().min(1),
    city: z.string().min(1),
    zipCode: z.string().regex(/^\d{5}$/),
  }),
  payment: z.object({
    cardNumber: z.string().regex(/^\d{16}$/),
    expiryDate: z.string().regex(/^\d{2}\/\d{2}$/),
    cvv: z.string().regex(/^\d{3}$/),
  }),
};

const fullSchema = z.object({
  ...stepSchemas.personal.shape,
  ...stepSchemas.address.shape,
  ...stepSchemas.payment.shape,
});

type FormData = z.infer<typeof fullSchema>;

const STEPS = ["Personal", "Address", "Payment", "Review"];

export function MultiStepForm() {
  const [step, setStep] = useState(0);

  const methods = useForm<FormData>({
    resolver: zodResolver(fullSchema),
    mode: "onChange",
  });

  const { trigger, getValues, handleSubmit } = methods;

  const validateStep = async () => {
    const fields = Object.keys(Object.values(stepSchemas)[step].shape);
    return trigger(fields as (keyof FormData)[]);
  };

  const nextStep = async () => {
    const isValid = await validateStep();
    if (isValid && step < STEPS.length - 1) {
      setStep((s) => s + 1);
    }
  };

  const prevStep = () => {
    if (step > 0) setStep((s) => s - 1);
  };

  const onSubmit = async (data: FormData) => {
    console.log("Submitting:", data);
  };

  return (
    <FormProvider {...methods}>
      <div className="mb-8">
        <div className="flex justify-between">
          {STEPS.map((label, i) => (
            <div
              key={label}
              className={`flex-1 text-center ${i <= step ? "text-blue-600" : "text-gray-400"}`}
            >
              <div className={`w-8 h-8 mx-auto rounded-full ${i <= step ? "bg-blue-600" : "bg-gray-200"}`}>
                {i + 1}
              </div>
              <span className="text-sm">{label}</span>
            </div>
          ))}
        </div>
      </div>

      <form onSubmit={handleSubmit(onSubmit)}>
        {step === 0 && <PersonalStep />}
        {step === 1 && <AddressStep />}
        {step === 2 && <PaymentStep />}
        {step === 3 && <ReviewStep data={getValues()} />}

        <div className="flex justify-between mt-8">
          <button type="button" onClick={prevStep} disabled={step === 0}>
            Previous
          </button>
          {step < STEPS.length - 1 ? (
            <button type="button" onClick={nextStep}>
              Next
            </button>
          ) : (
            <button type="submit">Submit</button>
          )}
        </div>
      </form>
    </FormProvider>
  );
}
```

## Server Action Integration

```typescript
// app/actions/form.ts
"use server";

import { z } from "zod";

const schema = z.object({
  email: z.string().email(),
  message: z.string().min(10),
});

export async function submitContact(formData: FormData) {
  const result = schema.safeParse({
    email: formData.get("email"),
    message: formData.get("message"),
  });

  if (!result.success) {
    return { errors: result.error.flatten().fieldErrors };
  }

  // Process form
  return { success: true };
}
```

This React Hook Form guide covers Zod validation, dynamic fields, multi-step wizards, and server integration.

When to Use This Prompt

This react-hook-form prompt is ideal for developers working on:

  • react-hook-form applications requiring modern best practices and optimal performance
  • Projects that need production-ready react-hook-form code with proper error handling
  • Teams looking to standardize their react-hook-form development workflow
  • Developers wanting to learn industry-standard react-hook-form patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their react-hook-form implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the react-hook-form code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this react-hook-form prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For react-hook-form projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...