register and handleSubmit
- React course
- Advanced
- Lesson 34/56
- 4 min
Learn to bind fields with register.
register details
The register function takes a field name and optional validation options. register('name', { required: true }) makes the field required.
Errors are kept in Name requiredformState.errors. You can show an error message with {errors.name && .
react-hook-form does not keep separate state per field; this is why it stays fast even with thousands of fields.
formState.errors
The formState.errors object holds the error for each field. You check the error type with errors.name?.type === 'required'.
You can give an optional message with register('name', { required: 'Name required' }); it is read via errors.name?.message.
This structure cuts code repetition and centralises error handling.
Practice Write a form with validation
Complete the skeleton. Write a Email requiredSignupForm component. Call useForm; get register, handleSubmit and formState: { errors }. Inside <form onSubmit={handleSubmit(onSubmit)}> put <input {...register('email', { required: true })} /> and {errors.email && . Add <button type="submit">Submit</button>. onSubmit = (data) => console.log(data). Add export default.
Starter code
import { useForm } from 'react-hook-form';
// Write SignupForm hereSample solution
import { useForm } from 'react-hook-form';
function SignupForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('email', { required: true })} />
{errors.email && <p>Email required</p>}
<button type="submit">Submit</button>
</form>
);
}
export default SignupForm;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where is a validation error kept?
- In window
- In localStorage
- In useState
- In formState.errors Correct answer
Explanation: Errors are in formState.errors.
2 required option
register('name', { ____: true });
register('name', { required: true });
Explanation: required makes the field required.
3 register and handleSubmit: match the terms
| Term | Meaning |
|---|---|
errors |
Error object |
register |
Binds field |
required |
Required |
message |
Error text |