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-hooks-localstorage

v1.3.1

Published

Complete React hooks library for localStorage with TTL, encryption, caching, sync, and advanced utilities.

Readme

🚀 React LocalStorage Hook Library

A complete and powerful React hooks library for managing localStorage with advanced features like TTL, cross-tab synchronization, caching, validation, and much more.

npm version npm downloads TypeScript License

✨ Key Features

  • 🔄 Cross-tab synchronization - Changes automatically reflected across all tabs
  • TTL (Time To Live) - Automatic data expiration
  • 🔐 Auto-encryption - Secure data storage with automatic encryption/decryption
  • 🎯 Specialized hooks - For arrays, objects, booleans, numbers
  • 📦 Smart caching - For APIs and expensive computations
  • 🛠️ Advanced utilities - Automatic cleanup, monitoring, backup
  • 🎨 TypeScript - Fully typed
  • 🌐 SSR Ready - Compatible with Next.js and other frameworks

📦 Installation

npm install react-hooks-localstorage
yarn add react-hooks-localstorage
pnpm add react-hooks-localstorage

🚀 Quick Start

Main Hook

import { useLocalStorage } from "react-hooks-localstorage";

function MyComponent() {
  const [name, { setValue, removeValue, isExpired }] = useLocalStorage(
    "user-name",
    "John Doe",
    { ttl: 24 * 60 * 60 * 1000 } // 24 hours
  );

  return (
    <div>
      <input
        value={name}
        onChange={(e) => setValue(e.target.value)}
        placeholder="Enter your name"
      />
      <button onClick={removeValue}>Clear</button>
      {isExpired() && <span>⚠️ Data expired!</span>}
    </div>
  );
}

Array Management

import { useLocalStorageArray } from "react-hooks-localstorage";

function TodoList() {
  const {
    array: todos,
    addItem,
    removeItem,
    clearArray
  } = useLocalStorageArray("todos", []);

  return (
    <div>
      <button onClick={() => addItem({ id: Date.now(), text: "New task" })}>
        Add
      </button>
      {todos.map((todo, index) => (
        <div key={todo.id}>
          {todo.text}
          <button onClick={() => removeItem(index)}>❌</button>
        </div>
      ))}
    </div>
  );
}

API Caching

import { useLocalStorageCache } from "react-hooks-localstorage";

function UserProfile({ userId }) {
  const { data, isLoading, error, refetch } = useLocalStorageCache(
    `user-${userId}`,
    () => fetch(`/api/users/${userId}`).then((res) => res.json()),
    {
      staleTime: 5 * 60 * 1000, // 5 minutes
      cacheTime: 30 * 60 * 1000 // 30 minutes
    }
  );

  if (isLoading) return <div>⏳ Loading...</div>;
  if (error) return <div>❌ Error: {error.message}</div>;

  return (
    <div>
      <h1>{data.name}</h1>
      <button onClick={refetch}>🔄 Refresh</button>
    </div>
  );
}

🎯 Available Hooks

Basic Hooks

  • useLocalStorage - Main hook with TTL and synchronization
  • useLocalStorageArray - Array management
  • useLocalStorageObject - Object management
  • useLocalStorageBoolean - Boolean management
  • useLocalStorageNumber - Number management
  • useLocalStorageMultiple - Multiple keys management

Advanced Hooks

  • useLocalStorageCache - Smart caching for APIs
  • useLocalStorageSync - Cross-component synchronization
  • useLocalStorageCompressed - Compression for large data
  • useLocalStorageAutoCleanup - Automatic cleanup

Utilities

  • LocalStorageManager - Advanced management
  • localStorageUtils - Various utilities

🔧 Advanced Configuration

const options = {
  ttl: 24 * 60 * 60 * 1000, // TTL in milliseconds
  syncAcrossTabs: true, // Cross-tab synchronization
  version: "1.0.0", // Version for migration
  serialize: JSON.stringify, // Custom serialization
  deserialize: JSON.parse, // Custom deserialization

  // 🔐 Encryption options (NEW!)
  autoEncrypt: true, // Enable automatic encryption
  secretKey: "your-secret-key" // Required when autoEncrypt is true
};

const [data, { setValue }] = useLocalStorage("key", defaultValue, options);

🔒 Encryption Configuration

When autoEncrypt is enabled, all data is automatically encrypted before storing and decrypted when retrieving:

// ✅ Secure - data is encrypted
const [secrets, actions] = useLocalStorage(
  "app-secrets",
  { apiKey: "", token: "" },
  {
    autoEncrypt: true,
    secretKey: process.env.REACT_APP_ENCRYPTION_KEY,
    ttl: 30 * 60 * 1000 // 30 minutes for sensitive data
  }
);

Security Notes:

  • The secretKey should be stored securely (environment variables recommended)
  • Encrypted data has a small performance overhead
  • TTL is especially recommended for encrypted sensitive data

📱 Practical Examples

Object Management

import { useLocalStorageObject } from "react-hooks-localstorage";

function UserProfile() {
  const {
    object: user,
    setProperty,
    updateObject,
    hasProperty,
    resetObject
  } = useLocalStorageObject("user-profile", {
    name: "",
    email: "",
    age: 0
  });

  return (
    <div>
      <input
        value={user.name}
        onChange={(e) => setProperty("name", e.target.value)}
        placeholder="Name"
      />
      <input
        value={user.email}
        onChange={(e) => setProperty("email", e.target.value)}
        placeholder="Email"
      />
      <button onClick={() => updateObject({ age: user.age + 1 })}>
        Increment Age
      </button>
      <button onClick={resetObject}>Reset</button>
    </div>
  );
}

Boolean Toggle

import { useLocalStorageBoolean } from "react-hooks-localstorage";

function ThemeToggle() {
  const {
    value: isDarkMode,
    toggle,
    setTrue,
    setFalse
  } = useLocalStorageBoolean("dark-mode", false);

  return (
    <div>
      <button onClick={toggle}>
        {isDarkMode ? "☀️ Light Mode" : "🌙 Dark Mode"}
      </button>
      <button onClick={setTrue}>Force Dark</button>
      <button onClick={setFalse}>Force Light</button>
    </div>
  );
}

Number Operations

import { useLocalStorageNumber } from "react-hooks-localstorage";

function Counter() {
  const {
    value: count,
    increment,
    decrement,
    multiply,
    divide,
    reset,
    clamp
  } = useLocalStorageNumber("counter", 0);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => increment()}>+1</button>
      <button onClick={() => increment(5)}>+5</button>
      <button onClick={() => decrement()}>-1</button>
      <button onClick={() => multiply(2)}>×2</button>
      <button onClick={() => divide(2)}>÷2</button>
      <button onClick={() => clamp(0, 100)}>Clamp 0-100</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

Cross-Component Synchronization

import { useLocalStorageSync } from "react-hooks-localstorage";

function ComponentA() {
  const { value, setValue, subscribe } = useLocalStorageSync(
    "shared-data",
    "initial"
  );

  useEffect(() => {
    const unsubscribe = subscribe((newValue) => {
      console.log("Data updated:", newValue);
    });
    return unsubscribe;
  }, [subscribe]);

  return <input value={value} onChange={(e) => setValue(e.target.value)} />;
}

function ComponentB() {
  const { value, setValue } = useLocalStorageSync("shared-data", "initial");

  return <div>Shared value: {value}</div>;
}

🔐 Encrypted Storage (NEW!)

Store sensitive data with automatic encryption:

import { useLocalStorage } from "react-hooks-localstorage";

function SecureComponent() {
  const [sensitiveData, { setValue, removeValue }] = useLocalStorage(
    "user-credentials",
    { username: "", password: "", ssn: "" },
    {
      autoEncrypt: true,
      secretKey: "your-secret-key-here",
      ttl: 15 * 60 * 1000 // 15 minutes for security
    }
  );

  return (
    <div>
      <input
        type="text"
        value={sensitiveData.username}
        onChange={(e) =>
          setValue({
            ...sensitiveData,
            username: e.target.value
          })
        }
        placeholder="Username"
      />
      <input
        type="password"
        value={sensitiveData.password}
        onChange={(e) =>
          setValue({
            ...sensitiveData,
            password: e.target.value
          })
        }
        placeholder="Password"
      />
      <p>✅ Data is automatically encrypted in localStorage!</p>
    </div>
  );
}

🌐 Compatibility

  • React: 16.8+ (hooks)
  • TypeScript: 4.0+
  • Browsers: All modern browsers
  • SSR: Next.js, Gatsby, Nuxt.js

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


Made with ❤️ by:

GitHub
LinkedIn