codez.guru

Why Integrate Zod with React Hook Form?

React Hook Form is one of the most popular form libraries in React — and Zod is the perfect pairing for it. Together, you get:

  • ✅ Powerful form control & performance (React Hook Form)
  • ✅ Type-safe, declarative validation (Zod)
  • ✅ Automatic TypeScript inference
  • ✅ Cleaner error handling

Installing Required Packages

Install the required packages:

npm install react-hook-form @hookform/resolvers zod

Creating the Zod Schema

import { z } from "zod";

export const LoginSchema = z.object({
  email: z.string().email("Invalid email"),
  password: z.string().min(6, "Password must be at least 6 characters"),
});

export type LoginInput = z.infer<typeof loginschema>;

Connecting Zod to React Hook Form

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { LoginSchema, LoginInput } from "@/schemas/login";

const LoginForm = () =&gt; {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm &lt;
  LoginInput &gt;
  {
    resolver: zodResolver(LoginSchema),
  };

  const onSubmit = (data: LoginInput) =&gt; {
    console.log("Form Data:", data);
  };

  return (
    <form onsubmit="{handleSubmit(onSubmit)}">
      <input placeholder="Email">
      {errors.email &amp;&amp; <p>{errors.email.message}</p>}

      <input type="password" placeholder="Password">
      {errors.password &amp;&amp; <p>{errors.password.message}</p>}

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

Displaying Field Errors

React Hook Form automatically:

  • Maps ZodError messages to your input fields
  • Uses the same keys (email, password, etc.)
  • Makes errors.field.message available for display

Simple and declarative:

{
  errors.email &amp;&amp; <p>{errors.email.message}</p>;
}

Summary

  • Use zodResolver() to plug Zod into React Hook Form
  • Keep schemas reusable across frontend and backend
  • Automatically handle validation + error display
  • Combine type inference with validation for a safer DX

Next: Lesson 20 – Final Thoughts, Best Practices, and Resources


Master the Code, Be the Guru!