Modern Form Handling in React with React Hook Form & Zod


Published at: September 10, 2022

Handling forms in React can sometimes feel cumbersome, especially when dealing with validations, state management, and submitting data. Thankfully, tools like React Hook Form have emerged to simplify the process. React Hook Form provides a clean, minimalistic approach to managing forms in React while improving performance by minimizing re-renders.

In this blog post, we’ll explore how React Hook Form has become the go-to solution for form management and how you can enhance your forms with Zod, a modern schema validation library that integrates smoothly with React Hook Form.


1. Why React Hook Form is the Best Solution for Forms

React Hook Form (RHF) has gained massive popularity in recent years due to its simplicity and performance. Before RHF, developers often relied on controlled components or third-party libraries like Formik to handle forms. However, these solutions can lead to unnecessary re-renders and verbose code. React Hook Form solves this by keeping form state uncontrolled by default, leading to fewer re-renders and improved performance.

Key Features of React Hook Form:

  • Uncontrolled Components: React Hook Form uses uncontrolled components to minimize re-renders. This means that instead of updating form state on every keystroke, RHF only updates the form state when necessary (e.g., on submit).
  • Minimal Re-renders: By leveraging React’s native ref system, React Hook Form avoids unnecessary re-renders, which is a major performance improvement over controlled components.
  • Easy Integration with UI Libraries: React Hook Form is extremely easy to integrate with various UI component libraries like Material UI, Ant Design, and Chakra UI.
  • Built-in Validation Support: React Hook Form provides easy-to-use hooks to handle validation, and it works seamlessly with popular validation libraries like Yup or Zod.

2. Setting Up React Hook Form

Let’s start by setting up React Hook Form in a simple form component:

npm install react-hook-form

Now, we can create a basic form:

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

const SimpleForm = () => {
  const { register, handleSubmit, formState: { errors } } = useForm();

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name</label>
        <input
          id="name"
          type="text"
          {...register('name', { required: 'Name is required' })}
        />
        {errors.name && <span>{errors.name.message}</span>}
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          type="email"
          {...register('email', { required: 'Email is required' })}
        />
        {errors.email && <span>{errors.email.message}</span>}
      </div>

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

export default SimpleForm;

In this example, we use useForm hook from React Hook Form to manage form state. We use the register function to register each input field, and handleSubmit to handle the form submission. The errors object keeps track of validation errors.


3. Adding Schema Validation with Zod

While React Hook Form provides basic validation, we can add a layer of complexity and more flexibility with Zod, a TypeScript-first schema validation library. Zod provides a clean, composable way to validate input values before submitting them.

Let’s integrate Zod into the form we just created for better validation:

Installing Zod:

npm install zod

Using Zod for Schema Validation:

Now let’s modify our form to use Zod for validation:

import React from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';

// Define the schema with Zod
const schema = z.object({
  name: z.string().min(1, 'Name is required'),
  email: z.string().email('Invalid email').min(1, 'Email is required'),
});

const FormWithZod = () => {
  const { register, handleSubmit, formState: { errors } } = useForm({
    resolver: zodResolver(schema), // Integrate Zod with React Hook Form
  });

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name</label>
        <input
          id="name"
          type="text"
          {...register('name')}
        />
        {errors.name && <span>{errors.name.message}</span>}
      </div>

      <div>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          type="email"
          {...register('email')}
        />
        {errors.email && <span>{errors.email.message}</span>}
      </div>

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

export default FormWithZod;

How Zod Helps with Validation:

  1. Schema Definition: Zod allows you to define a schema with methods like .min(), .email(), and more to validate the structure and type of the data.
  2. Zod Resolver: We use the zodResolver function from the @hookform/resolvers/zod package to integrate Zod’s schema validation into React Hook Form. The resolver ensures that the form values are validated against the schema before submitting.
  3. Clear Error Handling: Zod provides clear, descriptive error messages that are passed into the form via the errors object, helping the user to understand exactly what went wrong.

4. Why Zod for Validation?

You might wonder why Zod is a great choice for form validation in React:

  • TypeScript First: Zod is a TypeScript-first library, meaning it can infer the types from your schemas, making it perfect for TypeScript projects.
  • Composability: Zod schemas are easily composable, which is useful when you need to validate complex objects or arrays.
  • Minimal Boilerplate: Zod has a minimal and intuitive API, which means you can quickly define complex validation rules with little effort.

5. Final Thoughts

React Hook Form has revolutionized how we handle forms in React, providing a simple, performant solution that minimizes re-renders. By adding Zod for schema validation, we can take form handling to the next level, ensuring that our forms are not only performant but also robust and type-safe.

Together, React Hook Form and Zod offer a modern, scalable solution for form management in React applications. Whether you’re building a small form or handling complex forms with validations and dynamic inputs, this combination will save you time and effort.

By integrating React Hook Form with Zod, you can easily manage forms, validate data, and ensure your app runs smoothly even with the most complex forms.


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 *