Professional Approach to Forms
If your form has more than 3 fields, writing useState for each is a path to " spaghetti code " . You'll have to manually track errors, field clearing, and loading state.
React Hook Form (RHF) is a library that takes all this dirty work upon itself.
1. What's the Secret of Speed?
RHF uses uncontrolled logic (via refs) under the hood. This means while the user types in one field, the other 99 fields and the form component itself " rest " and don't redraw. This makes the interface incredibly responsive.
2. The register Method: Connecting Link
Instead of value and onChange, we simply " register " the input:
const { register, handleSubmit } = useForm();
<input {...register("firstName")} />
This short line makes the input part of a big system: now RHF knows about its value and can validate it.
3. Validation " Without Pain "
You can prescribe rules right during registration:
<input {...register("age", {
required: "Enter age",
min: { value: 18, message: "You must be over 18" }
})} />
4. Zod: Schemas for Large Projects
In real development, rules are often moved to separate schema files using the Zod library. This allows describing the form once and using this description both on frontend and backend. Example: " Email must be an email " , " Password minimum 8 characters " .
5. UX: Rules of Good Taste
A good form shouldn't " shout " at the user.
- Don't show errors immediately: Let the person finish typing. Use
mode: "onBlur"mode (validation on leaving the field). - Block the button: While data is being sent to the server, the button should be inactive (
isSubmitting). - Focus on error: If the form is large, RHF can scroll the page to the first incorrectly filled field itself.
RHF is not just a library for inputs, it's the standard of creating quality User Experience in web applications.