How to Use React Hook Form in Your Projects

Learn how to use React Hook Form to maintain cleaner code and simplify form management in React.

Published at: 11-21-2024

Forms are essential in many web applications, but managing form state and validation can get repetitive and error-prone as complexity grows. In this post, we'll explore how React Hook Form simplifies these processes.

Example 1: Simple Form with Basic React

To start, let's create a form using React without any additional libraries. We'll manage the form state using React's useState hook.

.jsx
import { useState } from "react";

function ExampleBasicReactForm() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [errors, setErrors] = useState({});

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    // Here we are doing simple validation for `name` and `email`
    let formErrors = {};
    if (name.length < 3) {
      formErrors.name = "Name must be at least 3 characters";
    }
    if (!email.includes("@")) {
      formErrors.email = "Email is not valid";
    }

    if (Object.keys(formErrors).length > 0) {
      setErrors(formErrors);
    } else {
      setErrors({});
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input id="name" value={name} onChange={(e) => setName(e.target.value)} />
      {errors.name && <p>{errors.name}</p>}

      <label htmlFor="email">Email:</label>
      <input
        id="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      {errors.email && <p>{errors.email}</p>}

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

export default BasicForm;

Output

There are many ways to manage forms; the above code snippet is just a basic example.

Explanation of Basic React Approach:

  • State management: we manage each input field(name and email) using indiviual useState hook.
  • Validation: We manually handle validation with the handleSubmit function, checking for errors and setting error messages in state
  • Submit: The handleSubmit function prevent the default submission and processes the the input values.

Although this approach works fine, but as your forms grow in complexity (e.g., more fields, more validation rules), the code can become repetitive and harder to maintain in project. so now let see using react hook form what we will get.

Refactoring with React Hook Form

Now, let's simplify the above form using React Hook Form.

First, We need to install the library

.bash
npm install react-hook-form

Here's how we can refactor the form.

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

export function ExampleReactHookForm() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">Name:</label>
      <input
        id="name"
        {...register("name", {
          required: "Name is required",
          minLength: {
            value: 3,
            message: "Name must be at least 3 characters long",
          },
        })}
      />
      {errors.name && <p>{errors.name.message}</p>}

      <label htmlFor="email">Email:</label>
      <input
        id="email"
        {...register("email", {
          required: "Email is required",
          pattern: {
            value: /^[^@]+@[^@]+\.[^@]+$/,
            message: "Email is not valid",
          },
        })}
      />
      {errors.email && <p>{errors.email.message}</p>}

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

Output

Key Differences with React Hook Form

  1. Reduced Boilerplate: No need for multiple useState hooks. The register function connects inputs to form state and also handle like onChange, onBlur and etc. so we don't need to handle manually.

  2. Simplified Validation: React Hook Form provides built-in validation capabilities, making it easier to enforce rules without cluttering your code.

  3. Error Handling: Error messages are handled via the formState.errors object and are automatically set based on the validation rules.

  4. Form Submission: The handleSubmit function ensures that validation is run before the form is submitted.

Benefits of Using React Hook Form

  • Cleaner Code: With fewer useState and onChange handlers, your code becomes easier to maintain and scale.
  • Improved Performance: React Hook Form minimizes re-renders by relying on uncontrolled components.
  • Custom Validation Support: React Hook Form supports schema-based validation libraries like zod for complex validations.