Convert Figma logo to code with AI

react-hook-form logoreact-hook-form

📋 React Hooks for form state management and validation (Web + React Native)

41,010
2,048
41,010
47

Top Related Projects

33,863

Build forms in React, without the tears 😭

4,465

Performance-focused API for React forms 🚀

🏁 High performance subscription-based form state management for React

3,625

🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS

Quick Overview

React Hook Form is a lightweight, performant, and flexible library for managing forms in React applications. It leverages React Hooks to simplify form validation and state management, reducing boilerplate code and improving overall performance.

Pros

  • Minimal re-renders and optimized performance
  • Easy to use and integrate with existing React projects
  • Supports both controlled and uncontrolled form inputs
  • Extensive validation options, including custom rules and async validation

Cons

  • Learning curve for developers new to React Hooks
  • May require additional setup for complex form scenarios
  • Limited built-in UI components (focuses on form logic)
  • Some advanced features might require additional plugins or extensions

Code Examples

  1. Basic form setup:
import { useForm } from "react-hook-form";

function MyForm() {
  const { register, handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName")} />
      <input {...register("lastName")} />
      <button type="submit">Submit</form>
    </form>
  );
}
  1. Form with validation:
import { useForm } from "react-hook-form";

function ValidatedForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("email", { required: true, pattern: /^\S+@\S+$/i })} />
      {errors.email && <span>This field is required and must be a valid email</span>}
      <button type="submit">Submit</form>
    </form>
  );
}
  1. Custom validation and error messages:
import { useForm } from "react-hook-form";

function CustomValidationForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register("username", {
          required: "Username is required",
          minLength: { value: 4, message: "Username must be at least 4 characters" }
        })}
      />
      {errors.username && <span>{errors.username.message}</span>}
      <button type="submit">Submit</form>
    </form>
  );
}

Getting Started

To start using React Hook Form in your project:

  1. Install the package:

    npm install react-hook-form
    
  2. Import and use in your React component:

    import { useForm } from "react-hook-form";
    
    function MyForm() {
      const { register, handleSubmit } = useForm();
      const onSubmit = data => console.log(data);
    
      return (
        <form onSubmit={handleSubmit(onSubmit)}>
          <input {...register("name")} />
          <input {...register("email")} />
          <button type="submit">Submit</button>
        </form>
      );
    }
    
  3. Add validation rules and error handling as needed.

Competitor Comparisons

33,863

Build forms in React, without the tears 😭

Pros of Formik

  • More mature and established library with a larger ecosystem
  • Built-in support for form validation and error handling
  • Easier integration with existing form libraries and UI components

Cons of Formik

  • Larger bundle size compared to React Hook Form
  • More verbose syntax and configuration required
  • Steeper learning curve for beginners

Code Comparison

Formik:

import { Formik, Form, Field } from 'formik';

<Formik initialValues={{ email: '' }} onSubmit={handleSubmit}>
  <Form>
    <Field name="email" type="email" />
    <button type="submit">Submit</button>
  </Form>
</Formik>

React Hook Form:

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

const { register, handleSubmit } = useForm();

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register('email')} type="email" />
  <button type="submit">Submit</button>
</form>

Both libraries offer powerful form handling capabilities, but React Hook Form provides a more lightweight and performant solution with a simpler API. Formik, on the other hand, offers more built-in features and better integration with existing form libraries. The choice between the two depends on project requirements, performance needs, and developer preferences.

4,465

Performance-focused API for React forms 🚀

Pros of Unform

  • Lightweight and performant, with minimal re-renders
  • Flexible architecture allowing easy integration with various UI libraries
  • Built-in support for complex, nested form structures

Cons of Unform

  • Smaller community and ecosystem compared to React Hook Form
  • Less comprehensive documentation and fewer examples available
  • Steeper learning curve for developers new to the library

Code Comparison

Unform:

import { Form } from '@unform/web';
import Input from './components/Input';

function MyForm() {
  function handleSubmit(data) {
    console.log(data);
  }

  return (
    <Form onSubmit={handleSubmit}>
      <Input name="email" />
      <button type="submit">Submit</button>
    </Form>
  );
}

React Hook Form:

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

function MyForm() {
  const { register, handleSubmit } = useForm();
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("email")} />
      <button type="submit">Submit</button>
    </form>
  );
}

Both libraries offer efficient form handling in React applications, but they differ in their approach and feature set. Unform provides a more flexible architecture and better support for complex form structures, while React Hook Form offers a larger ecosystem and easier learning curve for beginners.

🏁 High performance subscription-based form state management for React

Pros of React Final Form

  • More flexible and customizable for complex form scenarios
  • Better support for dynamic form fields and arrays
  • Smaller bundle size, which can be beneficial for performance

Cons of React Final Form

  • Steeper learning curve due to its more complex API
  • Less frequent updates and potentially slower bug fixes
  • Requires more boilerplate code for basic form setups

Code Comparison

React Final Form:

import { Form, Field } from 'react-final-form'

<Form
  onSubmit={onSubmit}
  render={({ handleSubmit }) => (
    <form onSubmit={handleSubmit}>
      <Field name="firstName" component="input" placeholder="First Name" />
      <button type="submit">Submit</button>
    </form>
  )}
/>

React Hook Form:

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

const { register, handleSubmit } = useForm()

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("firstName")} placeholder="First Name" />
  <button type="submit">Submit</button>
</form>

Both libraries offer efficient form handling in React applications, but React Hook Form generally provides a simpler API and better performance for most use cases. React Final Form shines in more complex scenarios requiring advanced customization. The choice between them depends on the specific needs of your project and your team's familiarity with each library.

3,625

🤖 Powerful and type-safe form state management for the web. TS/JS, React Form, Solid Form, Lit Form and Vue Form.

Pros of TanStack Form

  • Framework-agnostic, works with React, Vue, Solid, etc.
  • More flexible and customizable for complex form scenarios
  • Built-in support for nested forms and arrays

Cons of TanStack Form

  • Steeper learning curve due to its flexibility
  • Less opinionated, requiring more setup for basic forms
  • Smaller community and ecosystem compared to React Hook Form

Code Comparison

React Hook Form:

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

const { register, handleSubmit } = useForm();
const onSubmit = data => console.log(data);

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("firstName")} />
  <input type="submit" />
</form>

TanStack Form:

import { useForm } from "@tanstack/react-form";

const form = useForm({
  defaultValues: { firstName: "" },
  onSubmit: values => console.log(values),
});

<form.Provider>
  <form onSubmit={form.handleSubmit}>
    <form.Field name="firstName">
      {field => <input {...field.props} />}
    </form.Field>
    <button type="submit">Submit</button>
  </form>
</form.Provider>

Both libraries offer efficient form management in React applications. React Hook Form is more straightforward and easier to get started with, while TanStack Form provides greater flexibility and cross-framework compatibility at the cost of a steeper learning curve.

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS

Pros of resolvers

  • Provides schema validation integration with popular libraries like Yup, Zod, and Joi
  • Allows for more complex validation logic outside of the main form component
  • Enhances type safety when used with TypeScript

Cons of resolvers

  • Adds an additional dependency to the project
  • May increase bundle size slightly
  • Requires learning an additional API for schema validation

Code Comparison

react-hook-form:

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

const { register, handleSubmit } = useForm();
const onSubmit = (data) => console.log(data);

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("firstName", { required: true, maxLength: 20 })} />
</form>

resolvers (with Yup):

import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

const schema = yup.object().shape({
  firstName: yup.string().required().max(20),
});

const { register, handleSubmit } = useForm({
  resolver: yupResolver(schema),
});

<form onSubmit={handleSubmit(onSubmit)}>
  <input {...register("firstName")} />
</form>

The main difference is that resolvers moves validation logic to a separate schema, which can be more maintainable for complex forms but requires additional setup.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

npm downloads npm npm Discord

Get started | API | Form Builder | FAQs | Examples

Features

Install

npm install react-hook-form

Quickstart

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

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

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
      <input {...register('firstName')} />
      <input {...register('lastName', { required: true })} />
      {errors.lastName && <p>Last name is required.</p>}
      <input {...register('age', { pattern: /\d+/ })} />
      {errors.age && <p>Please enter number for age.</p>}
      <input type="submit" />
    </form>
  );
}

Sponsors

Thanks go to these kind and lovely sponsors!

Past sponsors

Backers

Thanks go to all our backers! [Become a backer].

Contributors

Thanks go to these wonderful people! [Become a contributor].

NPM DownloadsLast 30 Days