A lightweight React hook, useFormDataPersister, that automatically persists single-step or multi-step form data to localStorage
npm install react-formdata-persisterlocalStorage.
bash
npm install react-formdata-persister
`
๐ usage Example For both Single-step Form
`javascript
// Import the hook
import { useFormDataPersister } from "react-formdata-persister";
// Example: Single-step form
export default function ContactForm() {
// ๐ Every form must have a unique formKey
const { formData, updateField, resetForm } = useFormDataPersister({ formKey: "contact_form" });
const handleSubmit = () => {
console.log("Form submitted:", formData);
resetForm();
};
return (
);
}
`
๐ usage Example For Multi-step Form
`javascript
// Import the hook
import { useFormDataPersister } from "react-formdata-persister";
// Example: Multi-step form
export default function MultiStepForm() {
// ๐ Every form must have a unique formKey
const { formData, updateField, currentStep, nextStep, prevStep } = useFormDataPersister({
formKey: "signup_form",
steps: 3,
});
return (
{currentStep === 1 && (
placeholder="First Name"
value={formData.firstName || ""}
onChange={(e) => updateField("firstName", e.target.value)}
/>
)}
{currentStep === 2 && (
placeholder="Email"
value={formData.email || ""}
onChange={(e) => updateField("email", e.target.value)}
/>
)}
{currentStep === 3 && (
Review your info before submitting:
{JSON.stringify(formData, null, 2)}
)}
);
}
`
๐ usage Example For Reset Form
`javascript
๐งน Reset Form
Clear saved form data completely:
resetForm();
``