Skip to main content

Lesson 2 of 8

react-hook-form - Production Forms

react-hook-form is the React forms standard - it reduces re-renders to near zero by using uncontrolled inputs, provides excellent TypeScript integration, and works seamlessly with Zod for validation. The Controller API bridges it with custom input components.

35 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Advanced react-hook-form Patterns

Advanced react-hook-form Patterns
import { useForm, Controller, useFieldArray, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import Select from 'react-select';

// Schema for a job application form
const jobApplicationSchema = z.object({
  fullName: z.string().min(2, 'Full name required'),
  email: z.string().email('Valid email required'),
  yearsExperience: z.number({ coerce: true }).min(0).max(50),
  skills: z.array(z.object({ value: z.string(); label: z.string() })).min(1, 'Select at least one skill'),
  references: z.array(z.object({
    name: z.string().min(1, 'Name required'),
    email: z.string().email('Valid email'),
    relationship: z.string().min(1, 'Relationship required'),
  })).min(1, 'At least one reference required').max(3),
  coverLetter: z.string().min(100, 'Cover letter must be at least 100 characters'),
  availableImmediately: z.boolean(),
});

type JobFormData = z.infer<typeof jobApplicationSchema>;

const SKILL_OPTIONS = [
  { value: 'react', label: 'React' },
  { value: 'typescript', label: 'TypeScript' },
  { value: 'node', label: 'Node.js' },
  { value: 'graphql', label: 'GraphQL' },
];

function JobApplicationForm() {
  const {
    register,
    control,
    handleSubmit,
    watch,
    formState: { errors, isSubmitting, isValid, dirtyFields },
  } = useForm<JobFormData>({
    resolver: zodResolver(jobApplicationSchema),
    mode: 'onBlur',
    defaultValues: {
      references: [{ name: '', email: '', relationship: '' }],
      availableImmediately: false,
    },
  });

  // useFieldArray - dynamic list of references
  const { fields: refFields, append, remove } = useFieldArray({
    control,
    name: 'references',
  });

  // useWatch - watch a field without causing whole form to re-render
  const coverLetter = useWatch({ control, name: 'coverLetter', defaultValue: '' });

  async function onSubmit(data: JobFormData) {
    await submitApplication(data);
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* Standard text input */}
      <div>
        <label>Full Name</label>
        <input {...register('fullName')} />
        {errors.fullName && <span>{errors.fullName.message}</span>}
      </div>

      {/* Number input with coerce */}
      <div>
        <label>Years of Experience</label>
        <input type="number" {...register('yearsExperience', { valueAsNumber: true })} />
      </div>

      {/* Controller - wraps react-select (controlled 3rd-party component) */}
      <div>
        <label>Skills</label>
        <Controller
          control={control}
          name="skills"
          render={({ field }) => (
            <Select
              {...field}
              options={SKILL_OPTIONS}
              isMulti
              placeholder="Select your skills..."
              onChange={val => field.onChange(val)}
            />
          )}
        />
        {errors.skills && <span>{errors.skills.message}</span>}
      </div>

      {/* Dynamic field array - references */}
      <div>
        <label>References ({refFields.length}/3)</label>
        {refFields.map((ref, index) => (
          <div key={ref.id} style={{ border: '1px solid #e2e8f0', padding: 16, borderRadius: 8, marginBottom: 8 }}>
            <input {...register(`references.${index}.name`)} placeholder="Name" />
            {errors.references?.[index]?.name && <span>{errors.references[index].name.message}</span>}
            <input {...register(`references.${index}.email`)} placeholder="Email" type="email" />
            <input {...register(`references.${index}.relationship`)} placeholder="Relationship" />
            {refFields.length > 1 && (
              <button type="button" onClick={() => remove(index)}>Remove</button>
            )}
          </div>
        ))}
        {refFields.length < 3 && (
          <button type="button" onClick={() => append({ name: '', email: '', relationship: '' })}>
            + Add Reference
          </button>
        )}
      </div>

      {/* Textarea with live character count */}
      <div>
        <label>Cover Letter ({coverLetter.length}/2000 characters)</label>
        <textarea {...register('coverLetter')} rows={6} />
        {errors.coverLetter && <span>{errors.coverLetter.message}</span>}
      </div>

      {/* Checkbox */}
      <label>
        <input type="checkbox" {...register('availableImmediately')} />
        Available to start immediately
      </label>

      <button type="submit" disabled={isSubmitting || !isValid}>
        {isSubmitting ? 'Submitting...' : 'Submit Application'}
      </button>
    </form>
  );
}

Common Mistakes - react-hook-form

  • Rerendering the whole form to show validation - use `formState.errors` directly; RHF only re-renders the fields that have errors, not the entire form
  • Using Controller for native inputs - `Controller` is only needed for custom components; native inputs work with `register()`
  • Not setting `defaultValues` - RHF manages the difference between undefined and empty string; always set defaultValues to avoid uncontrolled โ†’ controlled warnings
  • Reading watch() for every field - `watch()` without arguments subscribes to ALL changes; use `useWatch` with specific names for better performance
  • Forgetting `valueAsNumber` for number inputs - without it, input values are strings; `register('age', { valueAsNumber: true })` or Zod's `z.coerce.number()` handles the conversion

Tip

Tip

Practice reacthookform Production Forms in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for react-hook-form - Production Forms

Practice Task

Note

Practice Task - (1) Write a working example of reacthookform Production Forms from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with reacthookform Production Forms is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • react-hook-form is the React forms standard - it reduces re-renders to near zero by using uncontrolled inputs, provides excellent TypeScript integration, and works seamlessly with Zod for validation.
  • Rerendering the whole form to show validation - use `formState.errors` directly; RHF only re-renders the fields that have errors, not the entire form
  • Using Controller for native inputs - `Controller` is only needed for custom components; native inputs work with `register()`
  • Not setting `defaultValues` - RHF manages the difference between undefined and empty string; always set defaultValues to avoid uncontrolled โ†’ controlled warnings

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done