To create a useFormUpdate()
hook in React for better form state management, you can follow this method:
import { useState } from 'react';
const useFormUpdate = (initialState) => {
const [formData, setFormData] = useState(initialState);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name]: value,
}));
};
return { formData, handleChange };
};
export default useFormUpdate;
Here's how you can use the useFormUpdate
hook in your components:
import React from 'react';
import useFormUpdate from './useFormUpdate'; // Assuming you've placed the hook in a separate file
const MyForm = () => {
const { formData, handleChange } = useFormUpdate({
name: '',
email: '',
phone: '',
message: '',
});
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission with formData
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
<input
type="text"
name="phone"
value={formData.phone}
onChange={handleChange}
placeholder="Phone"
/>
<textarea
name="message"
value={formData.message}
onChange={handleChange}
placeholder="Message"
/>
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
In this example:
We create the
MyForm
component.We use the
useFormUpdate
hook to keep track of the form's data, starting with some default values for the form fields.We get the
formData
andhandleChange
from theuseFormUpdate
hook.We use
formData
to fill in the input fields andhandleChange
to update the form's data when inputs change.We create a
handleSubmit
function to manage what happens when the form is submitted, using the data fromformData
.