Let’s create a custom hook for form validation :
1. Define the hook :<!-- notionvc: aea309ea-7b80-484c-b51c-6b88cfe5801d -->
import {useState } from 'react';
function useFormValidation(initialValues , validationSchema){
//
}
This hook takes two arguments: initial values (the initial values for the form fields) and validationSchema ( a schema that defines the validation rules for each field).
2. Manage form state :<!-- notionvc: c8adb092-c87d-47c7-92ff-277f0f877281 -->
const [values , setValues] = useState(initialValues);
const [errors , setErrors] = useState({});
const [isSubmitting , setIsSubmitting ] = useState(false);
This code creates three state variables : values, errors , submitting<!-- notionvc: 28c69dc2-d7c5-4d26-bac2-c935e9465143 -->
3. Handle input changes :<!-- notionvc: 9c78b01d-6185-455c-99da-29daeeb3547a -->
const handleChange = (event) => {
const {name , value } = event.target;
setValues({...values , [name] : value});
};
This function updates the values state when the user types something into a form field.<!-- notionvc: 025d5161-8b70-42d7-8b7c-00c81bc16712 -->
4. Validate the form :<!-- notionvc: ee9c9058-b5e8-4779-925b-6b1ef7f5497c -->
const handleSubmit = async (event) => {
event.preventDefault();
setIsSubmitting(true);
try {
await validateSchema.validate(values , { abortEarly: false });
}catch (errors) {
setErrors(errors.inner.reduce((acc , error ) => ({...acc , [error.path]:error.message }), {}));
} finally {
setIsSubmitting(false);
}
};
This function handles form submission.<!-- notionvc: 2c0e97ca-16c6-4169-9a4c-800e3bbbf786 -->
5. Return the hook :<!-- notionvc: de68c973-ee0b-4f86-8195-e2a366fbffb8 -->
return {
values ,
errors,
isSubmitting,
handleChange ,
handleSubmit,
};
This returns an object that can be used in your component to access the form values , errors , and submission status.
Now you can use this custom hook in your form component :<!-- notionvc: c3433526-afd0-4947-bf3b-f29c160bcf0a -->
import {useFromValidation } from './From';
function MyForm(){
const {values , errors , isSubmitting , handleChange , handleSubmit } = useFormValidation(
{ name: '' , email: '' },
);
return (
<form onSubmit = {handleSubmit}>
{ /* ...... form fields */ }
<button type = " submit " disabled= {isSubmitting}>Submit</button>
</form>
);
}
<!-- notionvc: 505d5ea1-effa-4d4f-8387-20d77bd3e5ad -->
<!-- notionvc: c0e36b10-e68d-4e09-bc9c-84c22e1f24ac -->