Skip to main content

Another Option: React Hook Form (Part 1) - A Look at Another Powerful Form Library #79

📖 Introduction

Following our exploration of Advanced Form Handling with Formik (Part 2), this article introduces another popular and powerful form library: React Hook Form. We will learn about the core concepts of React Hook Form, its key features, and how it differs from Formik.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • React Hooks, especially useState and useEffect.
  • Controlled and uncontrolled components.
  • npm or yarn for installing packages.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • The "Why" of React Hook Form: Understanding the problems React Hook Form solves and its focus on performance.
  • Core Concepts: An introduction to React Hook Form's core concepts, including the useForm hook.
  • Core Implementation: How to build a simple form using React Hook Form to manage state and submission.
  • Basic Validation: How to add basic validation to a React Hook Form.

🧠 Section 1: The Core Concepts of React Hook Form

React Hook Form is a library for building forms in React that is designed to be performant, flexible, and easy to use. It takes a slightly different approach than Formik, primarily by embracing uncontrolled components.

Key Features:

  • Performance: React Hook Form minimizes the number of re-renders that happen when a user interacts with a form, which can lead to significant performance improvements.
  • Lightweight: It has zero dependencies and a small footprint.
  • Developer Experience: It has a simple and intuitive API that is easy to learn and use.

At its core, React Hook Form provides a hook called useForm that gives you everything you need to manage a form.


💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's see how to build a simple form with React Hook Form.

2.1 - Installation

First, you need to install React Hook Form in your project:

npm install react-hook-form

2.2 - Your First React Hook Form

Here is a basic example of a login form built with React Hook Form:

// code-block-1.jsx
import React from 'react';
import { useForm } from 'react-hook-form';

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

const onSubmit = (data) => {
alert(JSON.stringify(data));
};

return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="email">Email Address</label>
<input id="email" {...register('email')} />
</div>
<div>
<label htmlFor="password">Password</label>
<input id="password" type="password" {...register('password')} />
</div>
<button type="submit">Submit</button>
</form>
);
}

export default LoginForm;

Step-by-Step Code Breakdown:

  1. import { useForm } from 'react-hook-form';: We import the useForm hook.
  2. const { register, handleSubmit } = useForm();: We call the useForm hook to get the register and handleSubmit functions.
  3. {...register('email')}: The register function is used to register the input with React Hook Form. It returns the necessary props (onChange, onBlur, name, ref) to connect the input to the form.
  4. handleSubmit(onSubmit): The handleSubmit function will call our onSubmit function with the form data when the form is submitted and validation has passed.

2.3 - Adding Basic Validation

React Hook Form makes it easy to add validation. You can pass validation rules to the register function.

// code-block-2.jsx
const { register, handleSubmit, formState: { errors } } = useForm();

// ...

<input
id="email"
{...register('email', { required: 'Email is required' })}
/>
{errors.email && <p>{errors.email.message}</p>}

Code Breakdown:

  1. formState: { errors }: We get the errors object from the formState.
  2. {...register('email', { required: 'Email is required' })}: We pass a validation object to the register function. In this case, we are making the email field required.
  3. {errors.email && <p>{errors.email.message}</p>}: We display the error message if there is an error for the email field.

💡 Conclusion & Key Takeaways

In this article, we've been introduced to React Hook Form and seen how it can be used to build performant and flexible forms in React. By embracing uncontrolled components, React Hook Form provides a powerful alternative to libraries like Formik.

Let's summarize the key takeaways:

  • React Hook Form is a performant and lightweight library for building forms in React.
  • It uses uncontrolled components to minimize re-renders.
  • The useForm hook is the core of React Hook Form, providing the register and handleSubmit functions.
  • Validation is handled by passing rules to the register function.

Challenge Yourself: To solidify your understanding, try to add a "confirm password" field to the form with validation to ensure it matches the password field.


➡️ Next Steps

You now have a basic understanding of React Hook Form. In the next article, "Another Option: React Hook Form (Part 2)", we will explore more advanced features of React Hook Form, including how to integrate with UI libraries and how to use it with schema validation libraries like Yup.

Thank you for your dedication. Stay curious, and happy coding!


glossary

  • React Hook Form: A library for building forms in React with a focus on performance and ease of use.
  • useForm: A React hook provided by React Hook Form for managing form state and submission.
  • Uncontrolled Component: A form element that maintains its own internal state, managed by the DOM.

Further Reading