As our applications get bigger and more complicated, it can be worthwhile to look into third-party libraries that can help to reduce boilerplate, standardize our code, and simplify complex problems.
Most React applications contain forms. If you are building a React application that contains complex forms, you might ask yourself, which form library (if any) should I use?
Only use a form library if it makes your life as a developer easier. Start your application without a form library, and if you find you are writing repetitive code with complex validation logic, think about installing a form library. If the most complex form in your application is your login or registration form, then you probably don’t need to use a third party form library.
*Note: the examples in this post are taken from the official documentation websites for the three form libraries.
React Hook Form is a relative newcomer to the React form library landscape. It takes a different approach than it’s competitors. While other form libraries like final-form and Formik rerender on every change event, React Hook Form embraces uncontrolled form validation. This reduces your number of rerenders to the bare minimum.
This also makes React Hook Form more performant than it’s competitors. However, unless you are making extremely complicated, long forms, I don’t believe that form library performance will make much of a difference for your users.
Let’s take a look at a login form made with React Hook Form.
To create this form, we use three parameters returned by our call to the useForm
hook: handleSubmit
, register
and errors
. To create a form input with React Hook Form, your input must have two properties: a name, and a ref. With register
, we can register our validation rules, and whether the field is required or not.
We can also define our form’s initial state by passing it as a parameter to the useForm
hook.
React Hook Form has no external dependencies and weighs in at only about 5KB. If you are looking for a performant, form library with minimal boilerplate, React Hook Form is a great choice.
#reactjs #javascript #coding #programming #react