As React developers, we constantly seek efficient and effective ways to manage form state, handle user input, and enhance the overall user experience. Not so long ago React world introduced React Form Hooks, which is a game-changer that simplifies form management and empowers developers to streamline their codebase.
In this blog post, we will delve into the “Why” and “How” of using React Form Hooks, uncovering the benefits and demonstrating the practical implementation steps.
Why we should use react-hook-form
There are a couple of reasons we should use react-hook-form, so let’s see the most important:
- Code Efficiency: Developers rejoice as react-hook-form reduces the amount of code required significantly, outshining competitors like formik and react-final-form.
- Optimized Re-renders: One standout feature is its use of refs instead of state, resulting in a smaller number of re-renders compared to alternative solutions.
- Swift Mounting Time: In comparison to other alternatives, react-hook-form boasts a shorter mounting time, contributing to a smoother and faster user experience.
- Seamless Integration with yup: The library seamlessly integrates with the yup schema validation library, offering a cohesive solution for combining custom validation schemas.
For a more in-depth comparison and detailed insights, be sure to explore the react-hook-form website: https://react-hook-form.com/
Comparison
Let’s start with a plain react form.
We’ll examine the following code, where we create a basic form without leveraging any external library:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [state, setState] = useState({
email: "",
password: ""
});
const handleInputChange = (event) => {
const { name, value } = event.target;
setState((prevState) => ({
...prevState,
[name]: value
}));
};
const handleSubmit = (event) => {
event.preventDefault();
console.log(state);
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<div className="form-control">
<label>Email</label>
<input
type="text"
name="email"
value={state.email}
onChange={handleInputChange}
/>
</div>
<div className="form-control">
<label>Password</label>
<input
type="password"
name="password"
value={state.password}
onChange={handleInputChange}
/>
</div>
<div className="form-control">
<label></label>
<button type="submit">Login</button>
</div>
</form>
</div>
);
}
The provided code establishes a simple form with ‘email’ and ‘password’ input fields, along with a submit button. The ‘handleInputChange’ function ensures that the component state accurately reflects user input.
Upon form submission, the ‘handleSubmit’ function logs the entered data to the console. However, as our form requirements evolve to include complex validations like mandatory fields, minimum lengths, and email format checks, the manual implementation of such validations would lead to increased code complexity.
In the upcoming exploration, we’ll introduce the react-hook-form library, demonstrating how it streamlines these processes, making our forms more manageable and scalable.
How to use react-hook-form
- Installation
Execute the following command from your terminal in you project to install react-hook-form:
# for npm
npm install react-hook-form@7.49.3
# for yarn
yarn add react-hook-form@7.49.3
In this instance, we’re opting for version 7.49.3 of the react-hook-form library, representing the latest release as of the writing of this article.
2. Creating basic form with react-hook-form
Firstly, import the useForm hook into your project:
import { useForm } from 'react-hook-form';
Utilize the useForm hook as follows:
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
Here’s a breakdown of the key elements:
- register: A function from the useForm hook that assigns tracking functionality to each input field, allowing react-hook-form to monitor changes in their values.
- handleSubmit: A function to be called when the form is submitted.
- errors: A nested property within the formState object that houses any validation errors, if present.
Now, let’s replace the contents of the App.js file with the following code:
import React from "react";
import { useForm } from "react-hook-form";
import "./styles.css";
export default function App() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-control">
<label>Email</label>
<input type="text" name="email" {...register("email")} />
</div>
<div className="form-control">
<label>Password</label>
<input type="password" name="password" {...register("password")} />
</div>
<div className="form-control">
<label></label>
<button type="submit">Login</button>
</div>
</form>
</div>
);
}
In this code snippet, the register
function is applied to each input field, such as:
<input type="text" name="email" {...register("email")} />
<input type="password" name="password" {...register("password")} />
By using the spread operator, react-hook-form automatically includes essential event handlers like onChange and onBlur, simplifying the code and enhancing the form’s functionality. Stay tuned as we delve deeper into the capabilities of react-hook-form, exploring advanced features and optimizations for your React forms.
Each input field is assigned a unique name to facilitate react-hook-form in tracking changes in the data. The handleSubmit
function manages form submission, sending user-entered data to the onSubmit
function, where the data is logged to the console. This structured approach ensures efficient form handling and validation with react-hook-form.
We can now start the project using npm start
or yarn start
Upon submission, user-entered details effortlessly appear in the console. Compared to the non-react-hook-form code, this implementation is notably simplified. No manual addition of value or onChange handlers is required, and state management is handled seamlessly by react-hook-form, allowing developers to focus on building robust React applications. Experience the elegance of form handling with react-hook-form, streamlining the development process.
3. Adding a validation
The last thing we’ll do is add a validation to our form.
import React from "react";
import { useForm } from "react-hook-form";
import "./styles.css";
export default function App() {
const {
register,
handleSubmit,
formState: { errors }
} = useForm();
const onSubmit = (data) => {
console.log(data);
};
return (
<div className="App">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="form-control">
<label>Email</label>
<input
type="text"
name="email"
{...register("email", {
required: "Email is required.",
pattern: {
value: /^[^@ ]+@[^@ ]+\.[^@ .]{2,}$/,
message: "Email is not valid."
}
})}
/>
{errors.email && <p className="errorMsg">{errors.email.message}</p>}
</div>
<div className="form-control">
<label>Password</label>
<input
type="password"
name="password"
{...register("password", {
required: "Password is required.",
minLength: {
value: 6,
message: "Password should be at least 6 characters."
}
})}
/>
{errors.password && (
<p className="errorMsg">{errors.password.message}</p>
)}
</div>
<div className="form-control">
<label></label>
<button type="submit">Login</button>
</div>
</form>
</div>
);
}
In this refined code, we’ve simplified the validation process by directly providing the error messages during validation setup. The error messages are seamlessly displayed using the errors
object, eliminating the need for additional conditional checks. This approach not only streamlines the code but also allows for easy integration of future validations. Note that, upon validation errors, the onSubmit
handler won't execute, and the respective input field will be automatically focused for a seamless user experience.
Summary
As you can see, integrating the react-hook-form library significantly simplifies the process of building dynamic and validated forms in your React applications. By leveraging the powerful useForm hook, you streamline form management, reduce code complexity, and enhance the overall user experience.
Of course, there’s more to explore. What I showed you are examples of the most common use cases, but you can check out more features at the website: https://react-hook-form.com/
I hope this guide on using react-hook-form has been informative and beneficial for your React development journey. If you have any further questions or need assistance, feel free to explore the documentation.
Until next time, happy coding! 👋🚀