DEV Community

Cover image for Formik vs. React Hook Form
Abel
Abel

Posted on

Formik vs. React Hook Form

Forms are crucial components of web applications. Information is mostly gotten from users using forms. Usually, Building interactive and engaging online apps requires developers to create forms that are both efficient and easy to use. React provides libraries that facilitate the handling of forms.

Two well-known React form libraries are Formik and React Hook Form. Although they both provide strong form management capabilities for React applications, their methods and advantages vary.

This post will assist you in selecting the one that best meets your requirements.

Formik

Formik is an advanced and extensively used form framework designed for React. It offers a thorough API for controlling the submission, validation, and status of forms. Its integration with Yup for schema-based validation, which streamlines the process, is one of its main advantages.

Key Features of Formik:

  1. Declarative Form Handling: Formik makes it easy to create and manage forms declaratively.
  2. Validation: Built-in support for Yup allows for powerful and reusable validation schemas.
  3. Field-Level Control: There is easy control over form fields, which makes it suitable for complex forms.

Setup:

  1. Install formik and yup in your react app
npm i formik yup
or
yarn i formik yup
Enter fullscreen mode Exit fullscreen mode
  1. import Formik, Field, Form, ErrorMessage from formik
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const SignupForm = () => {
  return (
    <Formik
      initialValues={{ email'', password: '' }}
      validationSchema={Yup.object({
        fullName: Yup.string().required('full name is required'),
        email: Yup.string().email('Invalid email address').required('Email is required'),
        password: Yup.string().required("Password is required")
      })}
      onSubmit={(values, { setSubmitting }) => {
          console.log(values);
          setSubmitting(false);
      }}
    >
      <Form>
        <label htmlFor="fullName">Full Name</label>
        <Field name="fullName" type="text" />
        <ErrorMessage name="fullName" />

        <label htmlFor="email">Email Address</label>
        <Field name="email" type="email" />
        <ErrorMessage name="email" />

        <label htmlFor="password">Password</label>
        <Field name="password" type="password" />
        <ErrorMessage name="password" />

        <button type="submit">Submit</button>
      </Form>
    </Formik>
  );
};
Enter fullscreen mode Exit fullscreen mode

Some advantages of using Formik includes:

  • Mature Ecosystem: Formik has extensive documentation, community support, and a lots of tutorials.
  • Robust Validation: Schema-based validation with Yup offers a clear and maintainable way to handle complex validation scenarios.

Disavantages:

  • Verbose: Requires more boilerplate code compared to some alternatives.
  • Performance: Performance is low in very large forms due to rerendering issues.

React Hook Form:

React Hook Form leverages React hooks for form management. It emphasizes performance and simplicity, providing a leaner and more intuitive API. React Hook Form is particularly praised for its minimal re-renders and ease of integration with existing React codebases.

Key Features of React Hook Form:

  • Hooks-Based: Utilizes React hooks for managing form state and validation, leading to cleaner and more concise code.
  • Minimal Re-Renders: Optimized to minimize re-renders, improving performance for large forms.
  • Easy Integration: Works seamlessly with existing HTML form elements and third-party component libraries.
  • Validation Flexibility: Offers multiple validation strategies, including native validation, custom validation, and integration with libraries like Yup.

Setup:

  1. Install react-hook-form into your project
npm i react-hook-form
or
yarn add react-hook-form
Enter fullscreen mode Exit fullscreen mode
  1. Import useForm from react-hook-form
import { useForm } from 'react-hook-form';
Enter fullscreen mode Exit fullscreen mode
  1. Create your component, using object destructure, get the register, handleSubmit and formState
function App() {
  const { register, handleSubmit, formState: { errors } } = useForm();

return (
  <form></form>
)
}
Enter fullscreen mode Exit fullscreen mode
  1. Add the input fields with register to capture field data and handle submit to process form submission
import { useForm } from 'react-hook-form';

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

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>

      <input {...register('fullName', { required: true })} />
      {errors.fullName && <p>Full name is required.</p>}

      <input {...register('email', { required: true, pattern: /^\w{3,}@\w{2,}\.\w{2,}/i })} />
      {errors.email && <p>Email format is invalid.</p>}

      <input {...register('password', { required: true } )} />
      {errors.password && <p>Password is required</p>}
      <input type="submit" />
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

Advantages:

  • Performance: Significantly reduces re-renders, making it highly efficient.
  • Simplicity: Less boilerplate and a more intuitive API, reducing development time.
  • Flexibility: Easy to integrate with existing form components and validation libraries.

Disadvantages:

  • Community Size: Being newer, it has a smaller community and fewer resources compared to Formik.

Conclusion

Choosing between Formik and React Hook Form depends on your specific needs and preferences. Formik is a solid choice for complex forms requiring robust validation and a mature ecosystem. React Hook Form, on the other hand, excels in performance and simplicity, making it ideal for projects where speed and ease of use are paramount.

As a frontend developer using react to build websites, it has been an awesome technology in building small and large scale website projects. Looking forward to the amazing things we will be building in the hng internship. https://hng.tech/internship, https://hng.tech/hire

Top comments (0)