Using React Hook Form for Better Forms in 2021

Published at: August 7, 2021

Building forms in React can often be a pain, especially when you’re dealing with complex validation, conditional inputs, or managing state for large forms. While React’s controlled components work well in many cases, they can lead to unnecessary re-renders and messy code.

React Hook Form simplifies form handling in React, reducing re-renders and providing better performance. In this post, we’ll dive into why React Hook Form is a great alternative to controlled components and how to leverage its power to build more efficient and clean forms.


1. Why React Hook Form is Better Than Controlled Components

In React, controlled components use useState or similar hooks to manage form input state. While this approach works, it comes with downsides:

  • Excessive Re-renders: Every time a form field changes, the entire form (or component) re-renders, which can hurt performance.
  • State Management Overhead: You have to manage the state for each form element manually, leading to more code and less clarity.

React Hook Form overcomes these issues by using uncontrolled components for most form inputs. It reduces the number of re-renders by handling form state in a more efficient way. Instead of binding the form’s state to every input field, React Hook Form registers form fields and manages their values and validation without causing unnecessary re-renders.

Benefits:

  • Improved Performance: React Hook Form reduces re-renders by only triggering updates for the changed fields.
  • Less Boilerplate: No need to manually manage state or write event handlers for every input field.
  • Simple Integration with Validation Libraries: It works seamlessly with libraries like Yup for schema-based validation.

2. How React Hook Form Works

React Hook Form uses the useForm hook to handle form state and validation. Here’s a basic setup:

  1. Install React Hook Form: Start by installing react-hook-form in your project:
   npm install react-hook-form
  1. Using the useForm Hook: The useForm hook initializes form management, including registration of form fields and validation.
   import { useForm } from 'react-hook-form';

   const MyForm = () => {
     const { register, handleSubmit, errors } = useForm();

     const onSubmit = (data) => {
       console.log(data);
     };

     return (
       <form onSubmit={handleSubmit(onSubmit)}>
         <input
           name="firstName"
           ref={register({ required: true })}
         />
         {errors.firstName && <span>This field is required</span>}

         <input
           name="lastName"
           ref={register({ required: true })}
         />
         {errors.lastName && <span>This field is required</span>}

         <button type="submit">Submit</button>
       </form>
     );
   };

   export default MyForm;

In this example:

  • register: Binds the input field to the form state.
  • handleSubmit: Handles form submission.
  • errors: Contains validation errors for the form fields.

3. Handling Validation with Less Re-renders

One of the most powerful features of React Hook Form is its built-in validation system. Unlike controlled components, which trigger re-renders on every change, React Hook Form only updates when a field’s validation state changes or when the form is submitted.

React Hook Form provides a couple of validation methods:

  • Validation using the register function: You can directly specify validation rules when registering a field.
  • Custom validation: You can pass a custom validation function for more complex rules.

Example of Simple Validation:

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

const MyForm = () => {
  const { register, handleSubmit, errors } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        name="email"
        ref={register({ 
          required: 'Email is required', 
          pattern: {
            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
            message: 'Invalid email address'
          } 
        })}
      />
      {errors.email && <span>{errors.email.message}</span>}

      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

In this example, the email field is validated with both a required rule and a pattern rule for email format. The error messages are displayed dynamically based on the validation result.


4. Integrating React Hook Form with Validation Libraries

To make form validation even more powerful, you can integrate Yup, a popular validation library, with React Hook Form. Yup allows you to define complex validation schemas and validate your forms with less code.

Example with Yup:

  1. Install Yup and React Hook Form’s Resolver:
   npm install yup @hookform/resolvers
  1. Integrating Yup Schema with React Hook Form:
   import { useForm } from 'react-hook-form';
   import { yupResolver } from '@hookform/resolvers/yup';
   import * as Yup from 'yup';

   const schema = Yup.object().shape({
     email: Yup.string().email('Invalid email').required('Email is required'),
     password: Yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'),
   });

   const MyForm = () => {
     const { register, handleSubmit, errors } = useForm({
       resolver: yupResolver(schema),
     });

     const onSubmit = (data) => {
       console.log(data);
     };

     return (
       <form onSubmit={handleSubmit(onSubmit)}>
         <input
           name="email"
           ref={register}
         />
         {errors.email && <span>{errors.email.message}</span>}

         <input
           name="password"
           type="password"
           ref={register}
         />
         {errors.password && <span>{errors.password.message}</span>}

         <button type="submit">Submit</button>
       </form>
     );
   };

   export default MyForm;

In this example, we’ve defined a Yup schema for validating email and password, and passed it to React Hook Form via the yupResolver. This makes validation rules more declarative and easy to manage.


Conclusion

Using React Hook Form to handle forms in React not only simplifies the process but also improves performance by reducing unnecessary re-renders. With its minimal API and seamless integration with popular validation libraries like Yup, it offers a more efficient way to build complex forms in React applications.

As you continue building more forms in React, consider using React Hook Form for a cleaner, more performant solution. It’s especially useful in larger applications where form validation and performance are critical.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *