Implementing a custom hook for handling automatic form saving in React involves using local storage or any other persistence mechanism to save the form data as the user inputs it. Here's a basic implementation:
javascriptimport { useState, useEffect } from 'react';
const useFormAutoSave = (formName, initialValues) => {
const [formValues, setFormValues] = useState(initialValues);
// Load saved form values from local storage when the component mounts
useEffect(() => {
const savedFormValues = localStorage.getItem(formName);
if (savedFormValues) {
setFormValues(JSON.parse(savedFormValues));
}
}, [formName]);
// Save form values to local storage whenever they change
useEffect(() => {
localStorage.setItem(formName, JSON.stringify(formValues));
}, [formName, formValues]);
// Function to update form values
const handleChange = (event) => {
const { name, value } = event.target;
setFormValues((prevValues) => ({
...prevValues,
[name]: value,
}));
};
// Function to reset form values
const resetForm = () => {
setFormValues(initialValues);
localStorage.removeItem(formName);
};
return { formValues, handleChange, resetForm };
};
export default useFormAutoSave;
Here's how you can use this hook in your components:
javascriptimport React from 'react';
import useFormAutoSave from './useFormAutoSave';
const MyForm = () => {
const { formValues, handleChange, resetForm } = useFormAutoSave('myForm', {
// Initial form values
name: '',
email: '',
// Add more fields as needed
});
return (
<form>
<input
type="text"
name="name"
value={formValues.name}
onChange={handleChange}
placeholder="Name"
/>
<input
type="email"
name="email"
value={formValues.email}
onChange={handleChange}
placeholder="Email"
/>
{/* Add more input fields here */}
<button type="button" onClick={resetForm}>
Reset Form
</button>
</form>
);
};
export default MyForm;
In this example:
useFormAutoSave
hook takes two arguments: formName
(a string identifier for the form) and initialValues
(an object containing the initial values of the form fields).useState
hook to manage the form values and useEffect
hook to save and load form values to/from local storage.handleChange
function updates the form values as the user types.resetForm
function resets the form values to their initial state and removes the saved data from local storage.This hook ensures that the form data is automatically saved to local storage as the user types, allowing them to continue where they left off even if they refresh the page or close the browser.