If you've ever struggled with managing forms in React, you're in the right place.
React Hook Form is a library lightweight and powerful that makes the process much simpler and more efficient.
Installation
To start using React Hook Form in your project, open the terminal and install the module directly in your application:
npm install react-hook-formIf you're using TypeScript (and I highly recommend you do!), you'll be happy to know that React Hook Form supports it natively. You don't need to install additional types.
The library already provides its type definitions, which will help you write safer code and avoid common errors.
Let's start with a simple example of how to use React Hook Form to create a login form:
import { useForm } from "react-hook-form";
function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("email", { required: true })} />
{errors.email && <span>Questo campo è obbligatorio</span>}
<input type="password" {...register("password", { required: true, minLength: 6 })} />
{errors.password && <span>La password deve essere lunga almeno 6 caratteri</span>}
<button type="submit">Login</button>
</form>
);
}In this example, you see how to use the register and handleSubmit functions, as well as how to handle basic errors. The register function is the heart of React Hook Form: it registers form fields and applies validation rules.
Advanced validation
Implement custom validation rules with specific error messages. This flexibility allows you to create forms with complex validations without having to write complicated logic.
Below, an example of validating a username field and a password field that, through a pattern, performs appropriate validation checks!
import { useForm } from "react-hook-form";
function AdvancedValidationForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register("username", {
required: "Username è obbligatorio",
minLength: { value: 4, message: "Minimo 4 caratteri" },
pattern: { value: /^[A-Za-z]+$/i, message: "Solo lettere sono permesse" }
})}
/>
{errors.username && <span>{errors.username.message}</span>}
<input
{...register("email", {
required: "Email è obbligatoria",
pattern: {
value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
message: "Indirizzo email non valido"
}
})}
/>
{errors.email && <span>{errors.email.message}</span>}
<button type="submit">Registra</button>
</form>
);
}Observing values with watch
One of the most powerful features of React Hook Form is watch. It allows you to observe changes in form fields in real-time:
import { useForm } from "react-hook-form";
function WatchExample() {
const { register, watch } = useForm();
const watchedValue = watch("esempio");
return (
<form>
<input {...register("esempio")} />
<p>Valore osservato: {watchedValue}</p>
</form>
);
}This is particularly useful for creating dynamic forms and controls or for showing real-time previews!
Async validation
In the real world, we often need to validate data against a server. React Hook Form makes this simple too, let's see an example:
import { useForm } from "react-hook-form";
function AsyncValidationForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const validateUsername = async (value) => {
await new Promise(resolve => setTimeout(resolve, 1000));
return value !== "admin" || "Username non disponibile";
};
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input
{...register("username", {
validate: validateUsername
})}
/>
{errors.username && <span>{errors.username.message}</span>}
<button type="submit">Registra</button>
</form>
);
}This example simulates a username check on the server, showing how to handle async validations in an elegant and clean way!
Form reset
Sometimes, you need to reset the form to its initial values. React Hook Form makes this simple with the reset function:
import { useForm } from "react-hook-form";
function ResetForm() {
const { register, handleSubmit, reset } = useForm();
const onSubmit = (data) => {
console.log(data);
reset(); // Resetta il form dopo l'invio
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
<input {...register("lastName")} />
<button type="submit">Invia</button>
<button type="button" onClick={() => reset()}>Reset</button>
</form>
);
}This functionality is incredibly useful for forms that need to be cleared after submission or on user request!
Conditional fields
Finally, let's look at how to handle conditional fields:
import { useForm } from "react-hook-form";
function ConditionalForm() {
const { register, watch } = useForm();
const showExtraField = watch("showExtra");
return (
<form>
<input type="checkbox" {...register("showExtra")} />
<label>Mostra campo extra</label>
{showExtraField && (
<input {...register("extraField")} placeholder="Campo extra" />
)}
</form>
);
}Conditional fields help us show or hide certain inputs based on other choices made in the form itself! An essential feature for creating dynamic and interactive forms!
React Hook Form transforms form management in React from a frustrating task to a smooth and pleasant process. With its intuitive API and powerful features, it allows you to create complex forms with less code and better performance.
From basic to async validation, from managing conditional fields to form reset, this library covers practically every form management scenario in React. And with its native support for TypeScript, it offers an even better development experience for those who prefer type safety.
Whether you're building a simple contact form or a complex multi-step wizard, React Hook Form has the tools you need to make the process simpler, faster and more enjoyable!
And you? Did you know React Hook Form? How do you build your forms in React?
