Claude
Skills
Sign in
Back

form-react

Included with Lifetime
$97 forever

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.

Web Devscripts

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 { useFieldA
Files: 3
Size: 32.5 KB
Complexity: 51/100
Category: Web Dev

Related in Web Dev