← Back to React, page 4

react-0070 · Medium mid

How does React Hook Form work, and why is it often preferred over hand-written controlled forms for large forms?

React Hook Form registers inputs as uncontrolled fields and reads their values from the DOM, so typing does not re-render the whole form. useForm returns register, handleSubmit and formState. You spread register('email', rules) onto an input, call handleSubmit(onValid) on the form, and read errors from formState. It supports schema validators such as Zod, nested and array fields, and Controller for controlled third-party inputs.

Full answer

A hand-written controlled form re-renders the component on every keystroke, and each field needs state and a handler. For forms with dozens of fields this is slow to write and sometimes slow to run.

React Hook Form (RHF) keeps values in refs attached to the inputs. const { register, handleSubmit, formState: { errors } } = useForm() gives you the tools. register('email', { required: 'Email is required' }) returns props (name, ref, onChange, onBlur) that you spread on the input. RHF listens to the DOM and stores values without re-rendering the component on each change.

handleSubmit(onValid) wraps your submit handler. It prevents the default, runs validation, and calls onValid with the values only when everything passes. Otherwise it fills formState.errors, which you render next to the fields. Validation modes control when it runs: onSubmit (default), onBlur, onChange or onTouched.

Rules can be inline (required, minLength, pattern, validate) or come from a schema with a resolver, for example Zod through @hookform/resolvers. A schema gives one source of truth shared with the server and types derived from it.

Other features: defaultValues for initial data, reset after saving, setError for server-side errors, useFieldArray for dynamic lists, watch to react to values (it re-renders, so use it sparingly), and Controller to connect controlled components such as a custom select.

Trade-offs: the uncontrolled model needs care when a field value must drive other UI instantly, and a form library is one more dependency. For a login form of two fields, plain controlled inputs are fine.

The example validates an email and a password.

jsx
import { useState } from 'react';
import { useForm } from 'react-hook-form';

export default function SignupForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm({ defaultValues: { email: '', password: '' } });
  const [message, setMessage] = useState('');

  function onValid(values) {
    setMessage('Signed up ' + values.email);
  }

  return (
    <form onSubmit={handleSubmit(onValid)} noValidate>
      <label>
        Email
        <input {...register('email', { required: 'Email is required', pattern: { value: /^\S+@\S+\.\S+$/, message: 'Enter a valid email' } })} />
      </label>
      {errors.email && <p role="alert">{errors.email.message}</p>}
      <label>
        Password
        <input type="password" {...register('password', { required: 'Password is required', minLength: { value: 8, message: 'Use at least 8 characters' } })} />
      </label>
      {errors.password && <p role="alert">{errors.password.message}</p>}
      <button type="submit">Sign up</button>
      {message && <output>{message}</output>}
    </form>
  );
}

The check submitted an empty form, then typed an email and an 8-character password and submitted again. Output of the run: empty submit: Email is required | Password is required valid submit: Signed up asha@example.com

Key points

  • RHF uses uncontrolled inputs and refs, so typing avoids whole-form re-renders.
  • register connects an input, handleSubmit validates and calls your handler.
  • Errors come from formState.errors. Validation can run on submit, blur or change.
  • Resolvers connect schema libraries such as Zod.
  • Use Controller for controlled components and useFieldArray for dynamic lists.

Common mistakes

  • Using watch for every field and losing the performance benefit.
  • Mixing register with a controlled value prop on the same input.
  • Not setting defaultValues, which leaves fields undefined.
  • Forgetting to show server-side errors with setError.
  • Treating client validation as a replacement for server validation.

Follow-ups

  • How does Controller differ from register, and when do you need it?
  • How would you connect a Zod schema as the resolver?
  • How would you build a dynamic list of fields with useFieldArray?

Tips

  • Explain the uncontrolled model. It is the reason RHF exists.
  • Name one limitation (instant dependent UI). It shows balance.
  • Mention schema validation shared with the server.