Handling Forms in React: Formik vs UseForm

Forms are an essential part of any web application, and handling them effectively can sometimes be a challenge for beginners in React. Fortunately, there are two popular libraries, Formik and UseForm, that simplify this task. In this post, we’ll dive deep into both React Formik and UseForm to help you understand how each one works, their differences, and when to use each. By the end of this article, you’ll be able to confidently choose the right tool for your next project.

Table of Contents:

  1. What Are Formik and UseForm?
  2. Why Do We Need Form Libraries in React?
  3. Setting Up a Basic Form with Formik
  4. Setting Up a Basic Form with UseForm
  5. Comparing Validation Techniques
  6. Handling Form Submission in Both Libraries
  7. Performance Considerations
  8. When to Use Formik vs UseForm
  9. Conclusion

1. What Are Formik and UseForm?

Formik and UseForm (from React Hook Form) are two popular libraries used to handle forms in React. While both libraries aim to simplify form management, they do so in slightly different ways.

  • Formik: A form management library focused on reducing boilerplate code and providing intuitive tools for handling form state, validation, and submission. It integrates well with Yup for schema validation.
  • UseForm (React Hook Form): A hook-based library that emphasizes performance and minimal re-renders. It provides a leaner API, making it faster and more efficient when dealing with large forms or complex input structures.

2. Why Do We Need Form Libraries in React?

Before diving into the specifics of Formik and UseForm, let’s quickly understand why form libraries are important in React:

  • Form State Management: React doesn’t offer built-in tools to manage form states. Libraries help by keeping track of field values, errors, and validation states.
  • Validation: Manually validating each form input can become tedious and error-prone. Libraries like Formik and UseForm provide easy-to-use validation mechanisms.
  • Performance: Handling forms with a lot of fields can lead to performance issues. Optimized libraries minimize unnecessary re-renders and improve the user experience.

3. Setting Up a Basic Form with Formik

Let’s first create a simple form with Formik. In this example, we’ll build a sign-up form with fields for name, email, and password.

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';

const SignUpForm = () => {
  const initialValues = { name: '', email: '', password: '' };

  const validationSchema = Yup.object({
    name: Yup.string().required('Name is required'),
    email: Yup.string().email('Invalid email').required('Email is required'),
    password: Yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'),
  });

  const onSubmit = (values) => {
    console.log('Form data', values);
  };

  return (
    <Formik initialValues={initialValues} validationSchema={validationSchema} onSubmit={onSubmit}>
      <Form>
        <Field name="name" type="text" />
        <ErrorMessage name="name" component="div" />

        <Field name="email" type="email" />
        <ErrorMessage name="email" component="div" />

        <Field name="password" type="password" />
        <ErrorMessage name="password" component="div" />

        <button type="submit">Sign Up</button>
      </Form>
    </Formik>
  );
};

export default SignUpForm;

Key Takeaways from Formik:

  • Formik Components: Formik, Field, and ErrorMessage make handling inputs and validation simpler.
  • Yup Validation: Integrating Yup allows for easy schema-based validation.

4. Setting Up a Basic Form with UseForm

Now, let’s create the same sign-up form with UseForm from React Hook Form.

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

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name', { required: 'Name is required' })} />
      {errors.name && <p>{errors.name.message}</p>}

      <input {...register('email', { required: 'Email is required', pattern: /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/ })} />
      {errors.email && <p>{errors.email.message}</p>}

      <input {...register('password', { required: 'Password is required', minLength: 6 })} />
      {errors.password && <p>{errors.password.message}</p>}

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

export default SignUpForm;

Key Takeaways from UseForm:

  • Register Hook: register helps tie inputs to form state.
  • Handle Submit: handleSubmit simplifies form submission logic.
  • FormState: errors allows easy access to validation messages.

5. Comparing Validation Techniques

Formik:

  • Relies on external validation libraries like Yup to define validation rules. This approach is highly flexible and integrates well with form schemas.

UseForm:

  • Offers inline validation using the register function, where rules like required and pattern can be directly embedded within input fields. It’s faster and more concise for simpler forms but can be less flexible for complex validation logic.

6. Handling Form Submission in Both Libraries

  • Formik: You define a separate onSubmit function within the Formik component to handle form submission. The onSubmit function is passed the form data directly.
  • UseForm: You use the handleSubmit function, which takes care of form submission, passing the data to the function you define.

Both libraries make it easy to manage form data, but UseForm has a slight performance edge as it minimizes re-renders during form interactions.

7. Performance Considerations

One key difference between the two libraries is their performance:

  • Formik: Re-renders the entire form on every input change, which can impact performance, especially in large forms.
  • UseForm: Minimizes re-renders by updating only the field that changes. This makes it more performant, particularly in forms with many inputs.

8. When to Use Formik vs UseForm

  • Use Formik if:
  • You prefer schema-based validation with Yup.
  • You’re building a simple or moderately complex form and don’t mind some re-renders.
  • You want built-in tools like ErrorMessage for displaying errors easily.
  • Use UseForm if:
  • You’re working on a large form with performance concerns.
  • You prefer hook-based APIs for better integration with React’s functional components.
  • You want more control over validation with minimal boilerplate.

9. Conclusion

Both Formik and UseForm are excellent form libraries that serve different needs in React applications. Formik excels in making form creation intuitive with its components and Yup integration, while UseForm shines in terms of performance and its lean API. By understanding the strengths and weaknesses of each, you can make an informed decision on which library best suits your project’s needs.

Happy form building!

Leave a Reply

Your email address will not be published. Required fields are marked *