Master complex form handling with React Hook Form, Zod validation, and dynamic fields in Google 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.This React Hook Form prompt is ideal for developers working on:
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.
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.
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.
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.