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 FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 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
Advanced React Hook Form Patterns

Advanced React Hook Form Patterns

Master complex form handling with React Hook Form, Zod validation, and dynamic fields in Google Antigravity

React Hook FormFormsZodTypeScriptValidation
by Antigravity Team
⭐0Stars
.antigravity
# Advanced React Hook Form Patterns for Google Antigravity

Building complex, performant forms requires sophisticated patterns. This guide covers advanced React Hook Form techniques optimized for Google Antigravity IDE and Gemini 3.

## Type-Safe Form Configuration

```typescript
// schemas/userForm.ts
import { z } from 'zod';

export const addressSchema = z.object({
  street: z.string().min(1, 'Street is required'),
  city: z.string().min(1, 'City is required'),
  state: z.string().length(2, 'Use 2-letter state code'),
  zipCode: z.string().regex(/^d{5}(-d{4})?$/, 'Invalid ZIP code'),
  country: z.string().min(1, 'Country is required'),
});

export const userFormSchema = z.object({
  personalInfo: z.object({
    firstName: z.string().min(2, 'First name must be at least 2 characters'),
    lastName: z.string().min(2, 'Last name must be at least 2 characters'),
    email: z.string().email('Invalid email address'),
    phone: z.string().regex(/^+?[ds-()]+$/, 'Invalid phone number').optional(),
    dateOfBirth: z.date().max(new Date(), 'Date cannot be in the future'),
  }),
  addresses: z.array(addressSchema).min(1, 'At least one address is required'),
  preferences: z.object({
    newsletter: z.boolean(),
    notifications: z.enum(['all', 'important', 'none']),
    theme: z.enum(['light', 'dark', 'system']),
  }),
  documents: z.array(z.object({
    name: z.string(),
    file: z.instanceof(File).optional(),
    url: z.string().url().optional(),
  })).optional(),
});

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

## Dynamic Form with Field Arrays

```typescript
// components/UserForm.tsx
import { useForm, useFieldArray, Controller, FormProvider } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { userFormSchema, type UserFormData } from '../schemas/userForm';

export function UserForm({ defaultValues, onSubmit }: UserFormProps) {
  const methods = useForm<UserFormData>({
    resolver: zodResolver(userFormSchema),
    defaultValues: defaultValues ?? {
      personalInfo: { firstName: '', lastName: '', email: '', dateOfBirth: new Date() },
      addresses: [{ street: '', city: '', state: '', zipCode: '', country: 'US' }],
      preferences: { newsletter: false, notifications: 'important', theme: 'system' },
    },
    mode: 'onBlur',
    reValidateMode: 'onChange',
  });

  const { control, handleSubmit, formState: { errors, isSubmitting, isDirty } } = methods;

  const { fields: addressFields, append, remove, move } = useFieldArray({
    control,
    name: 'addresses',
  });

  return (
    <FormProvider {...methods}>
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
        {/* Personal Info Section */}
        <fieldset className="border p-4 rounded-lg">
          <legend className="font-semibold">Personal Information</legend>
          
          <div className="grid grid-cols-2 gap-4">
            <FormField
              name="personalInfo.firstName"
              label="First Name"
              error={errors.personalInfo?.firstName?.message}
            />
            <FormField
              name="personalInfo.lastName"
              label="Last Name"
              error={errors.personalInfo?.lastName?.message}
            />
          </div>
          
          <Controller
            name="personalInfo.dateOfBirth"
            control={control}
            render={({ field }) => (
              <DatePicker
                selected={field.value}
                onChange={field.onChange}
                onBlur={field.onBlur}
                maxDate={new Date()}
              />
            )}
          />
        </fieldset>

        {/* Dynamic Addresses Section */}
        <fieldset className="border p-4 rounded-lg">
          <legend className="font-semibold">Addresses</legend>
          
          {addressFields.map((field, index) => (
            <AddressFieldGroup
              key={field.id}
              index={index}
              onRemove={() => remove(index)}
              onMoveUp={() => index > 0 && move(index, index - 1)}
              onMoveDown={() => index < addressFields.length - 1 && move(index, index + 1)}
              canRemove={addressFields.length > 1}
            />
          ))}
          
          <button
            type="button"
            onClick={() => append({ street: '', city: '', state: '', zipCode: '', country: 'US' })}
            className="btn-secondary"
          >
            Add Address
          </button>
        </fieldset>

        {/* Form Actions */}
        <div className="flex gap-4">
          <button
            type="submit"
            disabled={isSubmitting || !isDirty}
            className="btn-primary"
          >
            {isSubmitting ? 'Saving...' : 'Save'}
          </button>
          <button
            type="button"
            onClick={() => methods.reset()}
            disabled={!isDirty}
            className="btn-secondary"
          >
            Reset
          </button>
        </div>
      </form>
    </FormProvider>
  );
}
```

## Reusable Form Field Component

```typescript
// components/FormField.tsx
import { useFormContext, Controller } from 'react-hook-form';

interface FormFieldProps {
  name: string;
  label: string;
  type?: 'text' | 'email' | 'password' | 'number' | 'textarea';
  placeholder?: string;
  error?: string;
  required?: boolean;
}

export function FormField({ name, label, type = 'text', placeholder, error, required }: FormFieldProps) {
  const { register, formState: { touchedFields } } = useFormContext();
  const isTouched = touchedFields[name];

  return (
    <div className="form-group">
      <label htmlFor={name} className="form-label">
        {label}
        {required && <span className="text-red-500">*</span>}
      </label>
      
      {type === 'textarea' ? (
        <textarea
          {...register(name)}
          id={name}
          placeholder={placeholder}
          className={`form-input ${error && isTouched ? 'border-red-500' : ''}`}
        />
      ) : (
        <input
          {...register(name, { valueAsNumber: type === 'number' })}
          type={type}
          id={name}
          placeholder={placeholder}
          className={`form-input ${error && isTouched ? 'border-red-500' : ''}`}
        />
      )}
      
      {error && isTouched && (
        <p className="text-red-500 text-sm mt-1">{error}</p>
      )}
    </div>
  );
}
```

## Best Practices

1. **Colocate Validation**: Define Zod schemas alongside form components
2. **Use FormProvider**: Share form context across nested components
3. **Controlled Components**: Use Controller for third-party UI libraries
4. **Optimize Re-renders**: Use useWatch sparingly, prefer subscription pattern
5. **Handle Arrays**: Use useFieldArray for dynamic list fields
6. **Persist Drafts**: Auto-save form state to localStorage for recovery

Google Antigravity's Gemini 3 understands form patterns deeply and can generate complex form logic while maintaining type safety and validation integrity.

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...