JAVASCRIPT
Simplify Form Management with useForm Hook
A custom React hook for managing form state, input changes, and handling submissions with ease, reducing boilerplate in your form components.
import { useState, useCallback } from 'react';
const useForm = (initialState, onSubmitCallback) => {
const [values, setValues] = useState(initialState);
const handleChange = useCallback((event) => {
event.persist(); // For synthetic events in older React versions, though less critical in React 17+
setValues(prevValues => ({
...prevValues,
[event.target.name]: event.target.value,
}));
}, []);
const handleSubmit = useCallback((event) => {
if (event) event.preventDefault();
onSubmitCallback(values);
}, [values, onSubmitCallback]);
const resetForm = useCallback(() => {
setValues(initialState);
}, [initialState]);
return {
values,
handleChange,
handleSubmit,
resetForm,
setValues // Allow external updates if needed
};
};
// Example Usage:
// function MyForm() {
// const { values, handleChange, handleSubmit, resetForm } = useForm(
// { username: '', email: '' },
// (formData) => {
// console.log('Form submitted:', formData);
// alert(`Submitting: ${JSON.stringify(formData)}`);
// resetForm();
// }
// );
//
// return (
// <form onSubmit={handleSubmit}>
// <input
// type="text"
// name="username"
// placeholder="Username"
// value={values.username}
// onChange={handleChange}
// />
// <input
// type="email"
// name="email"
// placeholder="Email"
// value={values.email}
// onChange={handleChange}
// />
// <button type="submit">Submit</button>
// <button type="button" onClick={resetForm}>Reset</button>
// </form>
// );
// }
How it works: The useForm hook centralizes form state management. It utilizes useState to hold the current form values and provides `handleChange` to update values based on input `name` attributes, `handleSubmit` to invoke a provided callback with the form data, and `resetForm` to revert the form to its initial state. useCallback ensures these event handlers are stable across component renders, optimizing performance.