npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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.

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-draft

Peer dependencies:

npm install react react-hook-form

Quick 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:

  • password
  • token
  • accessToken
  • refreshToken
  • ssn
  • creditCard
  • cvv
  • secret

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:

  • sessionStorage adapter
  • custom adapter cookbook
  • improved last-saved metadata helpers
  • multi-tab synchronization via the storage event
  • optional beforeunload warning 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.