JAVASCRIPT
Build a Simple useForm Hook for React Input Management
Develop a basic React useForm hook to manage input states and handle changes efficiently, streamlining form development for common text inputs.
import { useState } from 'react';
function useForm(initialValues) {
const [values, setValues] = useState(initialValues);
const handleChange = (e) => {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
};
const resetForm = () => {
setValues(initialValues);
};
return {
values,
handleChange,
resetForm,
setValues // Optionally expose setValues for more control
};
}
// How to use it:
// function ContactForm() {
// const { values, handleChange, resetForm } = useForm({
// name: '',
// email: '',
// message: ''
// });
// const handleSubmit = (e) => {
// e.preventDefault();
// console.log('Form Submitted:', values);
// // Perform API call or other actions
// resetForm();
// };
// return (
// <form onSubmit={handleSubmit}>
// <input
// type="text"
// name="name"
// value={values.name}
// onChange={handleChange}
// placeholder="Your Name"
// />
// <input
// type="email"
// name="email"
// value={values.email}
// onChange={handleChange}
// placeholder="Your Email"
// />
// <textarea
// name="message"
// value={values.message}
// onChange={handleChange}
// placeholder="Your Message"
// />
// <button type="submit">Submit</button>
// <button type="button" onClick={resetForm}>Reset</button>
// </form>
// );
// }
How it works: The `useForm` hook initializes a `values` state with `initialValues`. It provides a `handleChange` function that can be directly used with input elements; it updates the corresponding field in the `values` state based on the input's `name` and `value`. A `resetForm` function is also provided to revert all fields to their `initialValues`, simplifying form state management.