UNPKG

snippet-hook

Version:

A simple and reusable custom hook for managing form state in React. The useForm hook allows you to easily manage form data, handle input changes, and reset the form state.

44 lines (41 loc) 1.19 kB
import { useState } from 'react'; const useForm = ({ initialValues, }) => { const [values, setValues] = useState(initialValues); const handleChange = (event) => { const { name, value } = event.target; setValues((prevState) => ({ ...prevState, [name]: value, })); }; const resetForm = () => { setValues(initialValues); }; return [values, handleChange, resetForm]; }; // import useForm from 'your-package-name'; // const MyFormComponent = () => { // const [formValues, handleInputChange, resetForm] = useForm({ // initialValues: { name: '', email: '' }, // }); // const handleSubmit = () => { // console.log(formValues); // }; // return ( // <form onSubmit={handleSubmit}> // <input // name="name" // value={formValues.name} // onChange={handleInputChange} // /> // <input // name="email" // value={formValues.email} // onChange={handleInputChange} // /> // <button type="button" onClick={resetForm}>Reset</button> // <button type="submit">Submit</button> // </form> // ); // }; export { useForm };