CodeBlanks Logo Icon CodeBlanks

What is react-hook-form?

Learn performant form management with react-hook-form.

What is react-hook-form?

react-hook-form is a library for performant form management. useForm manages form state without rerendering on every keystroke.

Other form libraries rerender the whole form on every keystroke; react-hook-form updates only the relevant field. This gives a clear performance boost in large forms.

You bind fields with register and handle submission with handleSubmit. Validation integrates with Zod or Yup.

register and handleSubmit

register binds an input to the form state. You spread {...register('name')} onto the input; react-hook-form tracks its name, value and changes.

handleSubmit is a function that wraps form submission. If the form is valid it calls the callback; otherwise it shows errors. It is used as <form onSubmit={handleSubmit(onSubmit)}>.

These two functions are the core of react-hook-form; most forms need only them.

Practice Write a simple form

Complete the skeleton. Write a NameForm component. Call useForm; get register and handleSubmit. Inside <form onSubmit={handleSubmit(onSubmit)}> put <input {...register('name')} /> and <button type="submit">Submit</button>. onSubmit should be (data) => console.log(data). Add export default.

Starter code

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

// Write NameForm here

Sample solution

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

function NameForm() {
  const { register, handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name')} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default NameForm;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does react-hook-form reduce?

  • The number of rerenders Correct answer
  • CSS size
  • HTML tag count
  • File count

Explanation: react-hook-form cuts unnecessary renders.

2 register call

Question
<input {...____('name')} />
Answer
<input {...register('name')} />

Explanation: register binds the field.

3 What is react-hook-form: match the terms

Term Meaning
useForm Creates form
register Binds field
handleSubmit Wraps submit
formState Holds errors

All lessons in Advanced