react-usedrafty
v2.1.0
Published
π A React hook to auto-save and restore form state using localStorage or sessionStorage.
Maintainers
Readme
react-usedrafty
React Drafty (π react-usedrafty) is a plug-and-play hook for autosaving form state to localStorage or sessionStorage.
No setup required. Restore drafts across page reloads β for any form.
π₯ Features
- β Auto-save form state (localStorage/sessionStorage)
- β Zero-config usage
- β Restore values on mount
- β Works with controlled forms (React state)
- β TypeScript supported
- β Small, dependency-free
- β Warn user before leaving with unsaved changes (optional)
- β Custom debounce/save interval
- β Clean up/reset support
- β
onRestorecallback when draft is loaded - β SPA navigation blocking (Next.js & React Router) if router object is provided
π¦ Installation
npm install react-usedrafty
# or
yarn add react-usedraftyπ Usage
1. Basic Example
import { useDrafty } from "react-usedrafty";
import { useState } from "react";
Variation 1 (Basic)
function ContactForm() {
const [formData, setFormData] = useState({ name: "", message: "" });
useDrafty("contact-form", formData, setFormData);
return (
<form>
<input
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>
<textarea
value={formData.message}
onChange={(e) => setFormData({ ...formData, message: e.target.value })}
/>
</form>
);
}
Variation 2 (Advance)
import { useDrafty } from "react-usedrafty";
function MyForm({ router }) {
const [formState, setFormState] = useState({ name: "", email: "" });
const { saveDraft, clearDraft, hasDraft, isDirty } = useDrafty(
"myForm",
formState,
setFormState,
{ debounce: 500, warnOnLeave: true, router }
);
const handleSubmit = () => {
// Send to API...
clearDraft({ submitted: true }); // β
clears and prevents restoring stale data
};
return (
<form onSubmit={handleSubmit}>
{/* form fields */}
</form>
);
}2. Custom Options
useDrafty("draft-key", data, setData, {
useSession: false, // Use sessionStorage instead of localStorage
delay: 1500, // Autosave delay (ms)
warnOnLeave: true, // Warn before leaving
onRestore: (draft) => console.log("Restored draft:", draft),
router: nextRouterInstance, // Optional: pass Next.js or React Router instance
});π API
useDrafty(key, state, setState, options?)
| Param | Type | Description |
|--------------|-------------|-------------|
| key | string | Storage key |
| state | object | Your form state |
| setState | function | State setter (e.g. useState) |
| options | object? | Optional config |
Options
useSession: Boolean β UsesessionStorageinstead oflocalStorage(default: false)debounce: Number β Debounce time in ms for saving drafts (defaults to 300ms if not provided; setting 0 still uses 300ms to avoid instant saves).warnOnLeave: Boolean/String/Function β Warn user before leaving with unsaved changes. (default: false)onRestore: Function β void β Callback when a draft is restored.router: Object β Optional Next.js or React Router instance to block SPA navigation
Returns
| Method | Type | Description |
|--------|------|-------------|
| saveDraft() | () => void | Saves current form state immediately. |
| clearDraft(options?: { submitted?: boolean }) | () => void | Clears the saved draft. If submitted: true is passed, sets a flag so the draft will not be restored next time the form is opened. |
| hasDraft | boolean | Whether a saved draft exists. |
| isDirty | boolean | Whether the current form state differs from the initially restored draft. |
β¨ What's New
- Added
onRestorecallback to run logic when draft is restored - Added
routeroption for SPA navigation blocking in Next.js and React Router - Improved
warnOnLeaveto accept custom message or condition function - Debounce improvements for smoother autosave
- Works with both localStorage and sessionStorage
π Troubleshooting
If you face this error:
Could not find a declaration file for module 'react'.Install types for React:
npm install --save-dev @types/reactπ§ͺ Example Directory
A full working example (/example) with a contact form is included in the repo.
Clone the repo and run locally to try it out!
cd example
npm install
npm startChangelog
v2.1.0
Enhancements
- Improved debounce behavior β Draft is only saved after the user stops typing for the specified debounce period. No more instant save on first keystroke.
- Form submission awareness β New
clearDraft({ submitted: true })option clears the draft and prevents restoring stale data when the form is reopened. - Skip restore if submitted β If the form was submitted previously, old drafts are skipped to avoid overwriting updated backend data.
- Auto-clear on SPA navigation β If a router is passed (Next.js Pages Router or React Router), drafts are cleared when navigating away.
- State reset after submission β If the user edits the form again after submission, the submitted flag is removed and drafts are saved again.
π License
MIT
βοΈ Author
Made by jbviaai with β€οΈ
Inspired by real-world use in feedback forms and checkout pages.
