Editor’s Note: This article was updated in July 2021 to reflect current technical statistic comparisons of both React Hook Form and Formik.
As JavaScript developers, we are all aware of the complexities and intricacies that we may encounter when working with React and forms. We have all struggled with form verbosity, form validations, and managing the state of the form and its components.
It was these struggles that led to the development of Formik. Formik addressed several shortcomings of its “predecessor,” Redux Form. Then, React Hook Form was released, which in turn addressed some of the shortcomings of Formik.
Formik outperformed Redux Form in terms of size, best practices, and performance, but in this article, we will see how Formik measures up against React Hook Form.
Below are the download statistics for React Hook Form and Formik. Formik still leads with well over 1 million weekly downloads:
But apart from the number of downloads, the above also shows the size, last updates, and the open issues, which are all good metrics on which to judge the libraries.
Based on the minzipped size, React Hook Form comes in at less than half the size of Formik, and it can also be deducted that both libraries are in active development because they get updated regularly. One thing to note is the difference in open issues. Here, React Hook Form outperforms Formik,
Next, let’s compare the codebase and the dependencies:
React Hook Form module composition:
So what does the above mean? The fewer dependencies a library has, the better. Take the infamous “left pad” disaster as an example. The left pad disaster occurred when one developer unpublished his npm modules and broke thousands of other modules that were dependent on it, so yes — fewer dependencies is definitely better.
So, to summarize:
Formik | React Hook Form | |
---|---|---|
Weekly Downloads | 1,486,953 | 893,036 |
Size | 12.6kB | 5.2kB |
Open Issues | 510 | 2 |
Dependencies | 9 | 0 |
Winner | 🥇 |
With its smaller size and zero dependencies, React Hook Form is the clear winner here.
Component re-renders are an important factor to consider when implementing any functionality in React. We want to avoid unnecessary re-render cycles as much as possible, as this could lead to major performance issues as an app grows. So let’s see how Formik measures up to React Hook Form:
But why is there such a large difference in the number of renders between the two libraries? And why hasn’t Formik yet caught up with React Hook Form? The answer relies on the architecture of the libraries and the way they are designed from the core. React Hook Form isolates input components from the rest, preventing the whole form to re-render for a single field change.
Other libraries, including Formik, rely on form updates to cascade changes to the inputs, and although it has some advantages in terms of flexibility, this has a huge cost on performance.
Another performance concern when developing React applications is the time to mount, which refers to the time it takes React to insert a component into the DOM. Naturally, we aim for the lowest time to mount possible because longer mounting times can cause perceived latencies and delays. Again, let’s square up Formik vs. React Hook Form:
Formik:
- No. of mounts: 6
- No. of committing changes: 1
- Total time: 2070ms
React Hook Form:
- No. of mounts: 1
- No. of committing changes: 1
- Total time: 1800ms
The above tests are based on a very simple form, so increasing the complexities would also cause the difference in time to mount to increase, but it is clear that React Hook Form outperforms Formik. In summary:
Formik | React Hook Form | |
---|---|---|
Re-renders | Updates occur on form level | Renders occur in isolation for particular fields |
No. of mounts | It mounts the form, some additional components, and uses a special component for fields | Only requires mounting the form |
No. of comitting changes | 1 | 1 |
Total mounting time | 2070ms | 1800ms |
Winner | 🥇 |
With its fewer re-renders and quicker time to mount, React Hook Form is the clear winner.
The tests are from the React Hook Form website, and the code and text explanations can be found there.
To evaluate the subtle differences and the caveats of each library, we are going to build a form with several different input types and validations:
Field Name | Field Type | Field Validation | Required |
---|---|---|---|
Username | Text | Max length = 20 | ✅ |
Name | Text | Max length = 50 | ✅ |
Valid Email (Pattern) | ✅ | ||
Mobile Number | Tel | Max length = 12 | ❌ |
Website | URL | None | ❌ |
Password | Password | Uppercase, lowercase, number/special char, and min. 8 chars | ✅ |
Gender | Radio | None | ❌ |
Date of Birth | Date | MM/DD/YYYY | ❌ |
About | Textarea | None | ❌ |
Subscribe to Newsletter | Checkbox | None | ❌ |
I added Bootstrap to the form for aesthetics, but also to demonstrate how easy it is integrated into each respective module. The submit event will log the form data to the console.
I did not include any additional libraries for validations or assisting with the state management; we will rely purely on the functionality of each library.
As I started with developing the form, I discovered the React Hook Form form builder:
This proved to be a game-changer, as it allows users to very easily create the form fields and their respective validations.
Note that the form builder is not a one-size-fits-all solution, but it does allow us to quickly bootstrap a form with generic HTML5 input fields. I needed to adjust a few minor things, especially when applying the Bootstrap elements and classes, but it did still save a lot of time.
Below is the CodeSandbox for the React Hook Form form:
React Hook Form Example
React Hook Form Example by sieg-g using react, react-dom, react-hook-form, react-scripts
I found the development to be really simple, and the great thing about React Hook Form is that it allows you to plug it into basically any framework or UI library.
In this example, we are using React Hook Form with a standard HTML5 form, inputs, and validation patterns. The error message integration also proved to be quick, simple, and easy to implement.
Below is an example of a form input, validation, and error message:
<div className="form-group"> <input className="form-control" type="text" placeholder="Username" {...register("Username", { required: true, maxLength: 20 })} /> {errors.Username && errors.Username.type === "required" && errorMessage(required)} {errors.Username && errors.Username.type === "maxLength" && errorMessage(maxLength)} </div>
Overall, I found React Hook Form to be a developer-friendly experience. I enjoy how light, clear, and concise the code is!
It is important to highlight that Formik has two different ways to build forms, one that makes use of a Formik
component and Formik-provided fields. This method harnesses the full power of Formik, enabling all its features and characteristics.
The second way to build a Formik form is by using the useFormik
hook, which is a simpler way to build forms, but comes with limitations and is recommended only for simpler scenarios.
Let’s now introduce our form using the Formik
component:
fervent-albattani-2kums
fervent-albattani-2kums by bajcmartinez using formik, react, react-dom, react-scripts
Just like React Hook Form, Formik also proved to be an excellent development tool and was simple to implement.
Below is an example of form input, validation, and an error message:
<div className="form-group"> <Field className="form-control" type="text" placeholder="Username" name="username" validate={validateUserName} /> {errors.username && touched.username && errorMessage(errors.username)} </div>
It is implemented in a very similar way to React Hook Form, but notice that Formik makes use of the <Field/>
component, unlike React Hook Form, which can be used with just HTML5 input elements.
Validation with Formik also needs to be explicitly developed and applied to each input, or through the help of validation libraries like Yup:
const validateUserName = value => { let error; if (!value) { error = required; } else if (value.length > 12) { error = maxLength; } return error; };
Both Formik and React Hook Form are powerful libraries that will enable you to build any form you may need. They are architectured differently, with React Hook Form leading in terms of performance and ease of implementation — in part thanks to being a newer library built for modern React applications.
It may not come as a surprise that I’m in favor of React Hook Form for the reasons presented in this post, but I’ve worked with Formik many times and always had pleasant experiences. Both libraries will get the job done well, and ultimately, it’s up to you to choose one in favor of the other. Keep in mind that if you are working with class components, you must choose Formik.
To summarize the discussion on this article:
<Field component="textarea" />
And the winner is:
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Formik | React Hook Form | |
---|---|---|
Winner | 🥇 |
Formik | React Hook Form | |
---|---|---|
React Native | ✅ | ✅ |
TypeScript | ✅ | ✅ |
Nested components | ✅ | ✅ |
Class components | ✅ | ❌ |
Code examples | ✅ | ✅ |
Clear documentation | ✅ | ✅ |
YUP integration | ✅ | ✅ |
Redux integration | ✅ | ✅ |
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.
19 Replies to "React Hook Form vs. Formik: A technical and performance comparison"
In an area where you meant to say hook forms did 1 re-render, you said 316,797 re-renders
That was a good pick up 🙂
Timing is everything! Formik just released v2 which is built on React Hooks. I think an update to this comparison is in order. Obviously the dependency graph may not change so much but moving away from the React class components _should_ help the re-render bloat.
Either way, thanks for a great comparison!
react-final-form is worth checking out too. It’s by the same author as redux-form. It’s very light and highly performant, it’s also been rewritten with hooks
React Hook Form author here 🙂
Unfortunately, that’s not the case when you switch from class component to functional in turns of re-rendering (if re-rendering is what you concerning). There are fundamental differences between react hook form and other controlled form libs out there. You can read more here:
https://react-hook-form.com/faqs/
React Hook Form, Formik or Redux Form?
Given that React Hook Form creates uncontrolled components, doesn’t that make it difficult to do instant (dynamic) field validation? How do you alert user when they’ve typed in maximum number of characters accepted by a field? Have a field “B” that is hidden unless field “A” is a specific value (one of several radio buttons)? Disable the submit button until all required fields have valid values? Do you have to descend to DOM-level solutions (js events or whatever) to handle these? This comparison article is quite rudimentary.
Thanks for your feedback Steve. a lot of your questions or concerns have already been address in the website documentation. If you are interest feel free to have a read 🙂 https://react-hook-form.com/advanced-usage At the end of day, the goal of React Hook Form is to make form building easier.
Hi Steve,
Thanks for the feedback, I will definitely keep it in mind when doing a comparison post again. You are totally correct, the article does only scratch the surface of the infinite possibilities which one can explore. But my goal was really to provide a broad overview of both frameworks, which should serve as a foundation, and then one can fill in the specific gaps if necessary. It might be valuable to do a deep dive into the React Hook Form and discuss some more complex scenarios.
Regarding your questions above, this can be very easily achieved with out of the box functionality of React Hook Form, like Bill said, have a look at the advanced usage docs, there are some great examples. Let me know if you get stuck, we can check it out!
Cheers,
Sieg
You can use HTML5 inputs as well with Formik, so this sentence: “It is implemented in a very similar way to React Hook Form, but notice that Formik makes use of the component, unlike React Hook Form, which can be used with just HTML5 input elements.” is not true.
Hey Sunpietro,
You are totally correct, the this was released in V2 which was released a few days after I wrote this :/
I will make amend!
Thanks.
Cheers,
Siegfried
You can use Formik v1 completely headless as well and render whatever components or HTML5 elements you desire. This is not a new feature in V2.
Great comparison! However, the statement that “Validation with Formik also needs to be explicitly developed and applied to each input” is misleading. Formik integrates natively with 3rd party validation libraries, particularly Yup. The ends result is syntax just as concise as (or even more than) React Hook Form’s:
https://jaredpalmer.com/formik/docs/guides/validation
Hey Zac, that’s a valid point. I guess we should narrow it down validation functionality “out the box” and that would be more precise. By the way, you can use schema validation for react hook form as well, check it out:
https://react-hook-form.com/api#validationSchem
Is the `React-Hook-Form` builder available on github? Would love to see the source code for the generation!
Here you go Paul: https://github.com/react-hook-form/react-hook-form-website 🙂
When I run code for both formik and react-hook-form, formik renders only once but react-hook-form renders number fields touched in form.
Could it be that the Formik re-render example is showing a lot of re-renders because by default it re-renders onChange for the underlying component? I think you can configure a component to re-render onBlur, in which case you’d get the same number of re-renders as React Hook Form – just one.
Which version of Formik do you use to compare with react-hook-form
Hi Antonio, I am new to react and just wondering if using formik is free or not.