Creating a form in React with react-hook-form vs useState

Elijah Koulaxis

August 16, 2023

ReactHookForm

Creating forms is a fundamental part of web development, enabling users to interact with your application and provide input. However, managing form state and handling user input efficiently can be a challenging task. In this article, we'll explore how you can leverage the power of react-hook-form to create forms in React that not only offer improved performance but also streamline the development process.

What is react-hook-form?

Traditional form handling in React often involves using useState to manage the state of form inputs and components. While this approach works, it can lead to complex and redundant code, as well as unnecessary re-renders. react-hook-form offers a more elegant solution by providing a performant and customizable way to manage form state and validation.

How does it work?

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

export function App() {
  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    console.log(data); // { firstName: '', lastName: '', email: '' }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} placeholder="First name" />
      <input {...register("lastName")} placeholder="last name" />
      <input {...register("email")} placeholder="email" />

      <input type="submit" />
    </form>
  );
}

Benefits of react-hook-form

Improved performance

One of the standout features of react-hook-form is its ability to isolate component re-renders. Unlike traditional form state management with useState, react-hook-form updates only the necessary components upon user input.

Efficient State Management

With react-hook-form, you can subscribe to individual input and form state updates without triggering unnecessary re-renders for the entire form. This level of control over state management ensures that your application remains responsive and efficient, even as the form grows in complexity.

Simplified Development

By abstracting away the complexities of form handling, react-hook-form simplifies the development process. You can focus on building the form itself and defining validation rules, rather than managing intricate state changes and input updates.

ReactPerformance

Adding Form Validation with react-hook-form

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

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="mb-4">
        <label className="block text-white text-sm mb-2" htmlFor="email">
          Email
        </label>

        <input
          className="w-full bg-gray-700 rounded-md p-2 text-white"
          type="email"
          id="email"
          placeholder="e.g. person@email.com"
          {...register("email", {
            required: "Email is required",
          })}
        />

        {errors.email && (
          <p>
            {errors.email.message?.toString()}
          </p>
        )}

      </div>

      {/* Other form inputs... */}

      <input type="submit" />
    </form>
  );
}

Validation Rules

We've used the register function to define validation rules for the "email" field. The required rule ensures that the user must provide an email address. If the input is left empty, the error message "Email is required" will be displayed.

Display Error Handling

To display error messages, we've utilized the errors object from the formState provided by react-hook-form. If there's an error for the "email" field, we're showing a red text message below the input.

Conclusion

By using this library, you make sure users have a smoother time interacting with your forms, your code becomes simpler, and your forms work better, faster and you're making your app run even smoother.

Tags:
Back to Home