react-form-draft
v0.1.1
Published
Persist and restore React form drafts with safe local storage defaults and first-class React Hook Form support.
Maintainers
Readme
react-form-draft
react-form-draft helps React applications persist and restore non-sensitive form drafts in the browser, with a first-class React Hook Form API.
It is designed for long forms, dashboard settings pages, onboarding flows, and other form-heavy screens where users may refresh, close a tab, or return later.
Installation
npm install react-form-draftPeer dependencies:
npm install react react-hook-formQuick Start
import { useForm } from 'react-hook-form';
import { useFormDraft } from 'react-form-draft';
interface ProfileFormValues {
firstName: string;
lastName: string;
bio: string;
}
export function ProfileForm() {
const form = useForm<ProfileFormValues>({
defaultValues: {
firstName: '',
lastName: '',
bio: '',
},
});
const draft = useFormDraft({
form,
key: 'profile-form',
});
return (
<form onSubmit={form.handleSubmit((values) => console.log(values))}>
<input {...form.register('firstName')} />
<input {...form.register('lastName')} />
<textarea {...form.register('bio')} />
{draft.hasDraft ? (
<div>
<button type="button" onClick={draft.restoreDraft}>
Restore draft
</button>
<button type="button" onClick={draft.discardDraft}>
Discard draft
</button>
</div>
) : null}
<button type="submit">Save</button>
</form>
);
}React Hook Form Example
import { useForm } from 'react-hook-form';
import { useFormDraft } from 'react-form-draft';
interface SettingsFormValues {
displayName: string;
email: string;
password: string;
token: string;
preferences: {
locale: string;
timezone: string;
};
}
export function SettingsForm() {
const form = useForm<SettingsFormValues>({
defaultValues: {
displayName: '',
email: '',
password: '',
token: '',
preferences: {
locale: 'en',
timezone: 'UTC',
},
},
});
const {
hasDraft,
draftMeta,
status,
restoreDraft,
discardDraft,
saveNow,
} = useFormDraft({
form,
key: 'settings-form',
version: 'settings-v2',
debounceMs: 800,
autoRestore: false,
clearOnSubmit: true,
exclude: [
'password',
'token',
],
});
return (
<form
onSubmit={form.handleSubmit(async (values) => {
await saveSettings(values);
})}
>
{hasDraft ? (
<aside>
<p>
Draft saved at{' '}
{draftMeta ? new Date(draftMeta.savedAt).toLocaleString() : 'unknown'}
</p>
<button type="button" onClick={restoreDraft}>
Restore
</button>
<button type="button" onClick={discardDraft}>
Discard
</button>
</aside>
) : null}
<input {...form.register('displayName')} />
<input {...form.register('email')} />
<input type="password" {...form.register('password')} />
<button type="button" onClick={saveNow}>
Save Draft Now
</button>
<button type="submit">Submit</button>
<output>{status}</output>
</form>
);
}API Reference
useFormDraft(options)
function useFormDraft<TFieldValues extends FieldValues>(
options: UseFormDraftOptions<TFieldValues>,
): UseFormDraftResult;Options
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| form | UseFormReturn<TFieldValues> | Required | React Hook Form instance returned by useForm. |
| key | string | Required | Unique storage key for the form draft. |
| debounceMs | number | 500 | Delay before writes are persisted. |
| version | string \| null | null | Drafts with a different version are ignored. |
| storage | DraftStorageAdapter | Safe localStorage adapter | Useful for tests or custom storage implementations. |
| include | Path<TFieldValues>[] | undefined | Only these fields are persisted. |
| exclude | Path<TFieldValues>[] | undefined | These fields are removed from persistence. |
| autoRestore | boolean | false | Restores immediately instead of exposing a manual prompt flow. |
| clearOnSubmit | boolean | true | Removes the draft after a successful submit. |
| removeCorruptedDraft | boolean | true | Removes malformed JSON drafts automatically. |
| resetOptions | Parameters<form.reset>[1] | undefined | Forwarded to React Hook Form reset during restore. |
include and exclude use dot-paths. When both are provided, include is applied first and exclude removes paths from that subset.
Return Value
| Field | Type | Notes |
| --- | --- | --- |
| hasDraft | boolean | true when a valid stored draft is currently available. |
| draftMeta | DraftMeta \| null | Includes key, version, and savedAt. |
| lastSavedAt | number \| null | Convenience alias for draftMeta?.savedAt. |
| status | 'idle' \| 'saved' \| 'restored' \| 'cleared' \| 'error' | Latest draft action result. |
| restoreDraft() | () => boolean | Restores the cached draft into the form and returns whether it succeeded. |
| discardDraft() | () => void | Removes the persisted draft without mutating current form values. |
| clearDraft() | () => void | Same behavior as discardDraft, useful after submit or reset flows. |
| saveNow() | () => void | Saves immediately, bypassing the debounce timer. |
Restore And Discard Flow
Manual restore mode is the default:
const draft = useFormDraft({
form,
key: 'article-editor',
autoRestore: false,
});
if (draft.hasDraft) {
return (
<div>
<button type="button" onClick={draft.restoreDraft}>
Restore draft
</button>
<button type="button" onClick={draft.discardDraft}>
Start fresh
</button>
</div>
);
}If you prefer silent restore:
useFormDraft({
form,
key: 'article-editor',
autoRestore: true,
});Include / Exclude Examples
Persist only part of a form:
useFormDraft({
form,
key: 'company-profile',
include: ['name', 'description', 'contact.email'],
});Exclude sensitive or irrelevant fields:
useFormDraft({
form,
key: 'payment-form',
exclude: [
'password',
'token',
'accessToken',
'refreshToken',
'ssn',
'creditCard',
'cvv',
'secret',
],
});Versioning Example
useFormDraft({
form,
key: 'product-form',
version: 'product-schema-v3',
});If the stored draft version does not match, the draft is ignored. This is useful when the form schema changes and older drafts should not be restored.
Custom Storage Adapter
The adapter interface is synchronous by design for the MVP:
interface DraftStorageAdapter {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
isAvailable?(): boolean;
}This keeps the package simple while leaving room for future adapters such as sessionStorage or IndexedDB-backed implementations.
SSR Note
react-form-draft is safe to import in SSR environments. The default adapter no-ops when window.localStorage is unavailable. Draft reads and writes happen only when the browser storage layer is available.
Security Note
This package stores drafts in browser storage. localStorage is not secure for secrets.
Do not persist passwords, tokens, payment data, national identifiers, or other sensitive fields unless you provide your own secure storage adapter and you fully understand the tradeoffs.
Recommended exclusions include:
passwordtokenaccessTokenrefreshTokenssncreditCardcvvsecret
This package never sends data over the network, does not use analytics, and does not attempt fake “encryption” inside browser storage.
Limitations
- The MVP is optimized for React Hook Form.
- Draft values should be JSON-serializable.
- The default adapter uses synchronous browser storage.
- Multi-tab draft synchronization is not included yet.
Build Output
The package ships both ESM and CJS builds so it can work cleanly in modern bundlers and older Node/CommonJS integrations. The runtime code stays dependency-light, and type declarations are generated alongside the bundle.
Roadmap
Planned post-MVP work:
sessionStorageadapter- custom adapter cookbook
- improved last-saved metadata helpers
- multi-tab synchronization via the
storageevent - optional
beforeunloadwarning helper - optional route-leave guard helper
- field transformers and custom serializers
- possible IndexedDB adapter for larger drafts
License
MIT
Maintainer Notes
Release and trusted publishing setup is documented in RELEASING.md. Security and publish-model notes are in SECURITY.md.
