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

v2.1.0

Published

πŸ“ A React hook to auto-save and restore form state using localStorage or sessionStorage.

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.

npm npm downloads license issues PRs Welcome


πŸ”₯ 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
  • βœ… onRestore callback 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 β€” Use sessionStorage instead of localStorage (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 onRestore callback to run logic when draft is restored
  • Added router option for SPA navigation blocking in Next.js and React Router
  • Improved warnOnLeave to 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 start

Changelog

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.