Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 14, 2022 05:52 pm GMT

React Forms Formik vs. Hook Form vs. Final Form

Hello Coders!

Forms are a crucial part of every application, from signing up, logging in, or collecting a survey from our users. Forms may seem simple but they are not. This article aims to provide a comparison of the top most-used React Forms with pros, cons, and code samples: Formik, React-Hook-Form and React-Final-Form. For newcomers, React is a super popular JS library for coding interactive user interfaces baked by Facebook.

Thanks for reading! Content provided by App Generator

  • Why do we need forms?
  • Intro to React (a short one)
  • Formik: pros, cons, and sample
  • React-Hook-Form: pros, cons, and sample
  • React-Final-Form: pros, cons, and sample
  • Conclusions & Resources
  • Free React Sample: Berry (use Formik)
  • Free React Sample: Datta Able (use Formik)

Why do we need forms

As mentioned above, forms might seem trivial and easy to code, but this fact is not true in all cases. Forms require validating the information provided by the user and coding multiple forms in different parts of our projects might be time-consuming. To solve this problem, we can use Form Libraries built on top of React released in the open-source ecosystem like Formik or `React- Final Form.

All mentioned libraries are easy to use and have (almost) all the functionalities we might need in our projects.

All we have to do is install and perform a quick setup of our preferred library. After that, we should be able to code much faster all forms required in the project and spend more time developing the actual business logic for the app.

What is React

React is an open-source UI library, built and maintained by Facebook. React breaks down a big application into smaller pieces called components. This component-based approach of React makes it more usable and maintainable.

As youll see React is not a framework its a library. That means its not a complete solution.

New to React? Check out this comprehensive React Starting Guide

JavaScript & React  Getting Starting Guide.

When you build an application with react youll need to use other external libraries to finish the application. This approach of React makes it more powerful because you have the freedom to choose whatever library you want for your app.

Examples of the libraries you might need to use are Axios for HTTP requests, Redux for managing states, and React-router-dom for Routing, React-hook-form for building forms.

Why choose the right Form Library?

Might be important what form library you choose for your application because some libraries are large and slow, and a lot of boilerplate codes or lack of support. These issues make using the library difficult.
For these reasons you have to be picky about the library you choose for your application. So, without any delay lets dive in and see the pros and cons of the top three React Form Libraries.

Well start with Formik.

Formik

Formik is an open-source React form library Authored by Jared Palmar. Jared built Formik out of frustration when he had to build more than 30 forms for his application. He wanted a standard way to build and manage all the forms in his application. For this he built Formik.

Open-Source React Form  Formik.

This library helps you with the three most annoying but important parts of building forms:

  • Getting values in and out of form state
  • Validation and error messages
  • Handling form submission

You can build a form easily with Formiks <Formik />, <Form />, <Field />, and <ErrorMessage /> components. Building a form with Formik is super easy. Later In this section, Ill show you how to build a form and validate it with Formik.
Before that lets look at a few pros and cons of Formik.

Formik Pros

  • Declarative components (, , )
  • 29k+ stars on Github
  • Integration with popular validation library: Yup
  • External UI Library support.

Formik Cons

  • 7 dependencies and 12.7 kB in size
  • 500+ Issues on GH
  • No built-in validation
  • A lot of boilerplate code (compared to React-hook-form)

Now that weve seen the pros and cons of Formik, lets build a simple form with `Formik to make it clear.

Install Formik

To build a form with Formik first well have to install it. We can do that with these commands:

$ npm install formik// OR$ yarn add formik

Form Source Code

import React from 'react';import ReactDOM from 'react-dom';import { Formik, Field, Form } from 'formik';const Basic = () => (  <div>    <h1>Sign Up</h1>    <Formik      initialValues={{        firstName: '',        lastName: '',        email: '',      }}      onSubmit={async (values) => {        await new Promise((r) => setTimeout(r, 500));        alert(JSON.stringify(values, null, 2));      }}    >      <Form>        <label htmlFor="firstName">First Name</label>        <Field id="firstName" name="firstName" placeholder="Jane" />        <label htmlFor="lastName">Last Name</label>        <Field id="lastName" name="lastName" placeholder="Doe" />        <label htmlFor="email">Email</label>        <Field          id="email"          name="email"          placeholder="[email protected]"          type="email"        />        <button type="submit">Submit</button>      </Form>    </Formik>  </div>);ReactDOM.render(<Basic />, document.getElementById('root'));

As you can see its a simple form. We didnt add validation yet. Ill do that in the next section.

To build the Form we called the <Formik> component. It takes two props: initialValues object which defines the initial values of the input fields and onSubmit method which handles form submission.

As you noticed, this form is self-declarative. That means the code describes whats going on. you dont need much effort to understand it.

Once we have finished the basic form, the next step is to add validation and constraint user to input relevant information.

Form Validation in Formik

One of the reasons to build Formik is to make form validation hassle-free. Formik supports synchronous and asynchronous Form-level and Field-level validation. It also provides schema-based Form-level validation through Yup. Yup is a very popular form validation library.

  • Form-level validation
  • Field-level validation

This is it. A complete Form built with Formik. For more resources, feel free to access:

React Hook Form

React-Hook-Form is a form library built around React hooks. This library takes a different approach to building Form. It isolates component re-renders by using uncontrolled components.

Unlike Formik, React-Hook-Form has zero dependencies. And the size is half the size of Formik ~= 8.6KB (minified + gzipped).

React Hook Form  Open-Source Library.

React Hook Form reduces the amount of code you need to write while removing unnecessary re-renders. To validate forms React-hook-form uses the standard Html based approach. You can build a form with React-hook-form easily with the useForm hook. Ill show you how to do that later in the post.

But now lets look at a few Pros and Cons of React Hook Form.

React-Hook-Form Pros

  • Less boilerplate code, Zero dependency
  • No issues on Github (what?)
  • 8.6kb size (minified and gzipped)
  • Out-of-the-box integration with UI libraries
  • Embraces native HTML form validation
  • Supports Yup form validation.

React-Hook-Form Cons

  • You need to use Yup or Built-in form validation

Install React-Hook-Form

$ npm install react-hook-form// OR$ npm install react-hook-form 

React-Hook-Form Sample

import { useForm } from "react-hook-form";const HookForm = () => {    const { register, handleSubmit } = useForm();    const handleRegistration = (data) => console.log(data);    return (      <div>        Hook Form    <form onSubmit={handleSubmit(handleRegistration)}>      <div>        <label>Email</label>        <input type="email" name="email" {..register('email')} />       </div>       <div>          <label>Password</label>          <input type="password" name="pass" {..register('pass')} />        </div>        <button>Submit</button>    </form>      </div>    );};

The handleSubmit handles the form submission and the register method helps you register an input field into React Hook Form so that it is available for validation, and its value can be tracked for changes.
This is a basic form. Now lets look at how you can validate forms with react-hook-form:

Form validation in React-Hook-Form

React Hook Form uses native HTML form validation to validate forms. To validate using you pass the validation rules to the register method.

The validation rules are:

  • required: indicates if the field is required or not.
  • minlength and maxlength set the minimum and maximum length for a string input value
  • min and max set the minimum and maximum values for a numerical value
  • pattern: takes a regular expression pattern to test the input.

Heres an example of how you validate forms in React-hook-form:

export default function App() {      return (    <form onSubmit={handleSubmit(onSubmit)}>      <input {..register("firstName", { required: true, maxLength: 20 })} />      <input {..register("lastName" , { pattern: /^[A-Za-z]+$/i })} />      <input type="number" {..register("age", { min: 18, max: 99 })} />      <input type="submit" />    </form>  );}

As you noticed this is just the initialization of validation. Well need a way to show the error message to the user.

import React from "react";import { useForm } from "react-hook-form";export default function App() {  const { register, formState: { errors }, handleSubmit } = useForm();  return (    <form onSubmit={handleSubmit(onSubmit)}>      <input {...register("firstName", { required: true })} />      {errors.firstName?.type === 'required' && "First name is required"}      <input {...register("lastName", { required: true })} />      {errors.lastName && "Last name is required"}      <input type="submit" />    </form>  );}

For more resources, related to React-hook-form, feel free to access:

React Final Form

React-Final-Form is a thin wrapper around Final-Form library. It doesn't have any other dependency than the Final Form and the size is really lightweight ~= 3.3kb (minified and gzipped).

You can build forms with React-Final-Form easily using the Form and Field component of React Final Form. Ill show you how to do that in a few moments.

React Final Form  Open-Source Library.

React-Final-Form Pros

  • Renders only the changed inputs
  • Only 3.2kb (minified and gzipped)
  • 6k+ stars on Github

React-Final-Form Cons

  • Has a peer dependency: Final Form.
  • A lot of boilerplate code
  • 350+ issues on Github

Install React-Final-Form

$ npm install final-form react-final-form// OR $ yarn final-form react-final-form

To build a form youll need to import the Form and Field component from react-final-form.

Form Sample Source Code

import { Form, Field } from 'react-final-form'import React from 'react'import { render } from 'react-dom'import Styles from './Styles'import { Form, Field } from 'react-final-form'const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))const onSubmit = async values => {  await sleep(300)  window.alert(JSON.stringify(values, 0, 2))}const App = () => (  <Styles>    <h1>React Final Form - Simple Example</h1>    <Form      onSubmit={onSubmit}      initialValues={{ firstname: '', lastname :''}}      render={({ handleSubmit, form, submitting, pristine, values }) => (        <form onSubmit={handleSubmit}>          <div>            <label>First Name</label>            <Field              name="firstName"              component="input"              type="text"              placeholder="First Name"            />          </div>          <div>            <label>Last Name</label>            <Field              name="lastName"              component="input"              type="text"              placeholder="Last Name"            />          </div>          <div className="buttons">            <button type="submit" disabled={submitting || pristine}>              Submit            </button>            <button              type="button"              onClick={form.reset}              disabled={submitting || pristine}            >              Reset            </button>          </div>        </form>      )}    />  </Styles>)render(<App />, document.getElementById('root')) 

As you can see this form is almost like the Formik form. To build a form the

component takes 3 props: initialValues, handleSubmit and render.

This is a basic form with React Final Form without validation. The validation in React Final Form is provided in two flavors, just like Formik

  • Form-level validation
  • Field-level validation

Because the validation code pattern is quite similar to Formik we will skip the samples for now. For more information related to React Final Form, please access:

So, Which one should you choose?

Choosing a form library should be dependent on what type of project you are building. Still, there are a few global points to choosing one library over another.

After all these comparisons If I start any project right now, Ill choose React-Hook-Form, because it has zero dependencies and less boilerplate code compared to React-Final-Form and Formik.

Formik and React-Final-Form make forms complicated while React-Hook-Form looks cleaner and more intuitive at first look. Also, the validation provided by React-Hook-Form uses less code to finish the job.

At the end of the day, feel free to choose Formik, or React-Final-Form for your project. Its completely up to your personal preference.

Sorry for this super long article. For those that are still here, the next section presents a few React Products that use production-ready React Forms.

React Berry (uses Formik)

Berry is a creative React Dashboard built using the Material-UI. It is meant to be the best User Experience with highly customizable feature-riched pages. It is a complete game-changer React Dashboard with an easy and intuitive responsive design on retina screens or laptops.

The product comes with a simple JWT authentication flow: login / register / logout powered by an open-source Node JS API Backend via Passport Library.

Berry  Open-Source React Project that uses Formik<br>

React Datta Able (uses Formik)

Datta Able is an open-source React Dashboard that provides a colorful and modern design. Datta Able React Free is the most stylized React Free Admin Template, around all other admin templates in the market.

Datta Able  Open-Source React Project that uses Formik.


Original Link: https://dev.to/sm0ke/react-forms-formik-vs-hook-form-vs-final-form-c1e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To