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

use-form-auto-save

v1.2.0

Published

A customizable React hook for automatically saving and restoring form data with support for localStorage, sessionStorage, and external APIs.

Readme

useFormAutoSave

npm codecov License

A custom React hook to automatically save form data seamlessly to localStorage, sessionStorage, or an external API, featuring debouncing, error handling, retry mechanisms, and restoration capabilities. It also integrates smoothly with React Hook Form.


Features

  • Auto-save form data with customizable debounce delay.
  • Flexible storage options:
    • Local Storage
    • Session Storage
    • External APIs
  • Robust error handling with automatic retry mechanisms.
  • Form data restoration from local/session storage.
  • Comprehensive debug logging for troubleshooting.
  • Works seamlessly with React Hook Form.

Installation

npm install use-form-auto-save
# or
yarn add use-form-auto-save

Usage

Basic Example (Local Storage)

import React, { useState } from "react";
import { useFormAutoSave } from "use-form-auto-save";

const AutoSaveExample = () => {
  const [formData, setFormData] = useState({ name: "", email: "" });
  const { isSaving, restoreFormData, setLastSavedData } = useFormAutoSave({
    formKey: "user-form",
    formData,
    storageType: "sessionStorage",
    debounceTime: 1000,
    debug: true,
  });

  // Restore form data on component mount
  useEffect(() => {
    const savedData = restoreFormData();
    if (savedData) {
      setFormData(savedData);
      setLastSavedData(savedData);
    }
  }, []);

  return (
    <>
      <input
        value={formData.name}
        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
      />
      <input
        value={formData.email}
        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
      />
      <p>{isSaving ? "Saving..." : "Saved"}</p>
    </>
  );
};

Advanced Example (API Integration)

import React, { useState } from "react";
import { useFormAutoSave } from "use-form-auto-save";
import { toast } from "react-toastify";
import apiClient from "./apiClient";

const FormWithApi = () => {
  const [formData, setFormData] = useState({ name: "", email: "" });

  const { isSaveSuccessful, resumeAutoSave, isAutoSavePaused } = useFormAutoSave({
    formKey: "userProfile",
    formData,
    storageType: "api",
    debounceTime: 2000,
    saveFunction: async (data) => await apiClient.saveUserProfile(data),
    onError: (err) => toast.error("Auto-save failed."),
    maxRetries: 5,
    debug: true,
  });

  return (
    <>
      <input
        value={formData.name}
        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
      />
      <input
        value={formData.email}
        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
      />
      {isAutoSavePaused && <button onClick={resumeAutoSave}>Retry Auto-Save</button>}
      <p>{isSaveSuccessful ? "All changes saved!" : "Saving failed."}</p>
    </>
  );
};

Additional Examples

Persist form data in session storage:

useFormAutoSave({ formKey: 'session-form', formData, storageType: 'sessionStorage' });

Persist form using React Hook Form:

useFormAutoSave({ formKey: 'rhf-form', control });

Enable debug logging:

useFormAutoSave({ formKey: 'debug-form', formData, debug: true });

Persist form data with a custom debounce interval:

useFormAutoSave({ formKey: 'debounced-form', formData, debounceTime: 3000 });

Persist form data to an API with error handling:

useFormAutoSave({
  formKey: 'api-form',
  formData,
  storageType: 'api',
  saveFunction: async (data) => await apiClient.save(data),
  onError: (error) => console.error("Auto-save error:", error)
});

Pause auto-saving on initial render:

useFormAutoSave({ formKey: 'skip-initial', formData, skipInitialSave: true });

API Reference

Config Options (AutoSaveConfig)

  • formKey (string, required) - Unique identifier for the form.
  • formData (object) - Form data for manual handling.
  • control (Control) - React Hook Form control object.
  • debounceTime (number) - Delay before saving after changes (default: 1000).
  • storageType ("localStorage" | "sessionStorage" | "api") - Storage medium (default: "localStorage").
  • saveFunction (function) - Custom async save function for APIs.
  • onError (function) - Callback on save error.
  • maxRetries (number) - Max retry attempts (default: 3).
  • skipInitialSave (boolean) - Skip auto-saving on initial render (default: false).
  • debug (boolean) - Enable debug logging (default: false).

Returned Values & Methods

  • restoreFormData() - Retrieve stored form data (local/session storage only).
  • resumeAutoSave() - Resume auto-saving if paused after retries.
  • isSaving (boolean) - Indicates saving status.
  • isSaveSuccessful (boolean) - Indicates last save success status.
  • isAutoSavePaused (boolean) - Indicates if auto-save is paused.
  • setLastSavedData(data) - Update internal tracking of last saved data.

Important Notes & Best Practices

  • API storage requires a saveFunction.
  • restoreFormData is unavailable for API storage.
  • Choose appropriate debounce intervals based on form complexity and user interactions.
  • Regularly test error-handling mechanisms to ensure reliability.

License

Released under the MIT License.