JAVASCRIPT
Build a Reusable Form State Manager with useForm Hook
Create a custom React useForm hook to simplify form state management, handle input changes, and manage submission logic in a declarative way.
import { useState } from 'react';
const useForm = (initialValues, onSubmit) => {
const [values, setValues] = useState(initialValues);
const handleChange = (event) => {
const { name, value, type, checked } = event.target;
setValues(prevValues => ({
...prevValues,
[name]: type === 'checkbox' ? checked : value,
}));
};
const handleSubmit = (event) => {
if (event) event.preventDefault();
onSubmit(values);
};
return {
values,
handleChange,
handleSubmit,
};
};
// Example Usage:
// function MyForm() {
// const submitForm = (formData) => {
// alert(JSON.stringify(formData, null, 2));
// };
//
// const { values, handleChange, handleSubmit } = useForm(
// { username: '', email: '', rememberMe: false },
// submitForm
// );
//
// return (
// <form onSubmit={handleSubmit}>
// <input
// type="text"
// name="username"
// value={values.username}
// onChange={handleChange}
// placeholder="Username"
// />
// <input
// type="email"
// name="email"
// value={values.email}
// onChange={handleChange}
// placeholder="Email"
// />
// <label>
// Remember Me:
// <input
// type="checkbox"
// name="rememberMe"
// checked={values.rememberMe}
// onChange={handleChange}
// />
// </label>
// <button type="submit">Submit</button>
// </form>
// );
// }
How it works: The `useForm` hook simplifies form handling by centralizing state and change logic. It initializes form values with `initialValues` and provides `values` for input fields, a `handleChange` function to update state based on input changes (handling text and checkboxes), and a `handleSubmit` function that prevents default form submission and calls the provided `onSubmit` callback with the current form data.