react-form-persist
v1.0.2
Published
Seamlessly persist and restore React form state with localStorage. Simple, lightweight, and hassle-free.
Maintainers
Readme
useFormPersist
A custom React hook for persisting form data in localStorage. Automatically saves and restores form state, ensuring a seamless user experience even after page reloads.
Installation
Install via npm:
npm install react-form-persistOr with Yarn:
yarn add react-form-persistUsage
First, import the hook into your component:
import { useFormPersist } from "react-form-persist";Basic Example
import React from "react";
import { useFormPersist } from "react-form-persist";
const MyForm = () => {
const [formData, setFormData, clearPersistedData] = useFormPersist("myForm", {
name: "",
email: "",
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prev) => ({ ...prev, [name]: value }));
};
return (
<div>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Name"
/>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
<button onClick={clearPersistedData}>Clear Data</button>
</div>
);
};
export default MyForm;API
useFormPersist(key, initialData)
- key (
string): The key under which the form data is stored inlocalStorage. - initialData (
object): The initial state of your form data.
Returns:
- formData (
object): The current form data. - setFormData (
function): Function to update the form data. - clearPersistedData (
function): Clears the data from both state andlocalStorage.
Clearing Persisted Data
To remove the stored data and reset the form to its initial state, call clearPersistedData:
<button onClick={clearPersistedData}>Clear Data</button>This removes the data from both local state and localStorage.
License
MIT
