form-react
Production-ready React form patterns using React Hook Form (default) and TanStack Form with Zod integration. Use when building forms in React applications. Implements reward-early-punish-late validation timing.
What this skill does
# Form React
Production React form patterns. Default stack: **React Hook Form + Zod**.
## Quick Start
```bash
npm install react-hook-form @hookform/resolvers zod
```
```tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// 1. Define schema
const schema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Min 8 characters')
});
type FormData = z.infer<typeof schema>;
// 2. Use form
function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm<FormData>({
resolver: zodResolver(schema),
mode: 'onBlur' // Reward early, punish late
});
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<input {...register('email')} type="email" autoComplete="email" />
{errors.email && <span>{errors.email.message}</span>}
<input {...register('password')} type="password" autoComplete="current-password" />
{errors.password && <span>{errors.password.message}</span>}
<button type="submit">Sign in</button>
</form>
);
}
```
## When to Use Which
| Criteria | React Hook Form | TanStack Form |
|----------|-----------------|---------------|
| Performance | ✅ Best (uncontrolled) | Good (controlled) |
| Bundle size | 12KB | ~15KB |
| TypeScript | Good | ✅ Excellent |
| Cross-framework | ❌ React only | ✅ Multi-framework |
| React Native | Requires workarounds | ✅ Native support |
| Built-in async validation | Manual | ✅ Built-in debouncing |
| Ecosystem | ✅ Mature (4+ years) | Growing |
**Default: React Hook Form** — Better performance for most React web apps.
**Use TanStack Form when:**
- Building cross-framework component libraries
- Need strict controlled component behavior
- Heavy async validation (username checks)
- React Native applications
## React Hook Form Patterns
### Basic Form
```tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { loginSchema, type LoginFormData } from './schemas';
export function LoginForm({ onSubmit }: { onSubmit: (data: LoginFormData) => void }) {
const {
register,
handleSubmit,
formState: { errors, isSubmitting, touchedFields }
} = useForm<LoginFormData>({
resolver: zodResolver(loginSchema),
mode: 'onBlur', // First validation on blur (punish late)
reValidateMode: 'onChange' // Re-validate on change (real-time correction)
});
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<div className="form-field">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
autoComplete="email"
aria-invalid={!!errors.email}
{...register('email')}
/>
{touchedFields.email && errors.email && (
<span role="alert">{errors.email.message}</span>
)}
</div>
<div className="form-field">
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
autoComplete="current-password"
aria-invalid={!!errors.password}
{...register('password')}
/>
{touchedFields.password && errors.password && (
<span role="alert">{errors.password.message}</span>
)}
</div>
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Signing in...' : 'Sign in'}
</button>
</form>
);
}
```
### Reusable Form Field Component
```tsx
// FormField.tsx
import { useFormContext } from 'react-hook-form';
import { ReactNode } from 'react';
interface FormFieldProps {
name: string;
label: string;
type?: string;
autoComplete?: string;
hint?: string;
required?: boolean;
children?: ReactNode;
}
export function FormField({
name,
label,
type = 'text',
autoComplete,
hint,
required,
children
}: FormFieldProps) {
const {
register,
formState: { errors, touchedFields }
} = useFormContext();
const error = errors[name];
const touched = touchedFields[name];
const showError = touched && error;
const showValid = touched && !error;
return (
<div className={`form-field ${showError ? 'error' : ''} ${showValid ? 'valid' : ''}`}>
<label htmlFor={name}>
{label}
{required && <span aria-hidden="true">*</span>}
</label>
{hint && <span className="hint">{hint}</span>}
{children || (
<input
id={name}
type={type}
autoComplete={autoComplete}
aria-invalid={!!error}
aria-describedby={error ? `${name}-error` : undefined}
{...register(name)}
/>
)}
{showError && (
<span id={`${name}-error`} role="alert" className="error-message">
{error.message as string}
</span>
)}
</div>
);
}
```
### Using FormProvider for Nested Components
```tsx
// Form wrapper
import { FormProvider, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
export function CheckoutForm() {
const methods = useForm({
resolver: zodResolver(checkoutSchema),
mode: 'onBlur'
});
return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<ContactSection />
<ShippingSection />
<PaymentSection />
<button type="submit">Place Order</button>
</form>
</FormProvider>
);
}
// Nested section component
function ContactSection() {
return (
<fieldset>
<legend>Contact Information</legend>
<FormField name="email" label="Email" type="email" autoComplete="email" required />
<FormField name="phone" label="Phone" type="tel" autoComplete="tel" />
</fieldset>
);
}
```
### Watching Values (Real-time)
```tsx
import { useForm, useWatch } from 'react-hook-form';
function RegistrationForm() {
const { register, control } = useForm();
// Watch password for strength meter
const password = useWatch({ control, name: 'password', defaultValue: '' });
return (
<form>
<input type="password" {...register('password')} />
<PasswordStrength password={password} />
</form>
);
}
```
### Conditional Fields
```tsx
import { useFormContext, useWatch } from 'react-hook-form';
function ConditionalField({ watchField, condition, children }) {
const { control } = useFormContext();
const value = useWatch({ control, name: watchField });
if (!condition(value)) return null;
return <>{children}</>;
}
// Usage
<ConditionalField watchField="hasCompany" condition={(val) => val === true}>
<FormField name="companyName" label="Company Name" />
</ConditionalField>
```
### Async Validation (Username Check)
```tsx
import { useForm } from 'react-hook-form';
function RegistrationForm() {
const { register, setError, clearErrors } = useForm();
const checkUsername = async (username: string) => {
if (username.length < 3) return;
const response = await fetch(`/api/check-username?u=${username}`);
const { available } = await response.json();
if (!available) {
setError('username', { type: 'manual', message: 'Username is taken' });
} else {
clearErrors('username');
}
};
return (
<input
{...register('username')}
onBlur={(e) => checkUsername(e.target.value)}
/>
);
}
```
### Form Reset
```tsx
function EditProfileForm({ defaultValues }) {
const { reset, handleSubmit } = useForm({ defaultValues });
// Reset to new values
useEffect(() => {
reset(defaultValues);
}, [defaultValues, reset]);
// Reset to initial values
const handleCancel = () => reset();
return (
<form>
{/* fields */}
<button type="button" onClick={handleCancel}>Cancel</button>
<button type="submit">Save</button>
</form>
);
}
```
### Array Fields (Dynamic)
```tsx
import { useFieldARelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.