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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@brushy/localstorage

v1.0.2

Published

Powerful abstraction for local state management

Downloads

200

Readme

@brushy/localstorage

Coverage - Statements Coverage - Branches Coverage - Functions Coverage - Lines

npm downloads npm bundle size npm version

A robust and efficient TypeScript library for local storage management in browsers, with support for compression, expiration, JSON serialization, and lazy loading.

Real-World Problem Solving

Here's how @brushy/localstorage compares to other solutions in solving common real-world problems:

| Problem | @brushy/localstorage | localStorage | localforage | Other Solutions | | ----------------- | -------------------------- | -------------- | --------------- | --------------- | | Type Safety | ✅ Full TypeScript support | ❌ No types | ⚠️ Basic types | ⚠️ Varies | | Compression | ✅ Automatic compression | ❌ None | ❌ None | ⚠️ Manual | | TTL Support | ✅ Built-in expiration | ❌ None | ❌ None | ⚠️ Manual | | Large Data | ✅ Lazy loading & chunks | ❌ Size limits | ✅ IndexedDB | ⚠️ Varies | | Performance | ✅ Optimized caching | ✅ Native API | ⚠️ Async only | ⚠️ Varies | | Events | ✅ Fine-grained control | ⚠️ Limited | ✅ Good support | ⚠️ Basic | | Serialization | ✅ Smart JSON handling | ⚠️ Basic | ✅ Good support | ⚠️ Manual |

Legend:

  • ✅ Fully Supported/Optimal
  • ⚠️ Partial/Varies
  • ❌ Limited/Problematic

Features

  • 🔒 Strong Typing: Fully written in TypeScript for a safe development experience
  • 🗜️ Intelligent Compression: Automatic compression for large data, optimizing storage usage
  • ⏱️ TTL (Time-to-Live): Easily set expiration for your stored data
  • 🔄 JSON Serialization: Store and retrieve complex objects without worries
  • 🦥 Lazy Loading: Load large datasets only when needed
  • 🪝 React Hooks: Seamless integration with React applications
  • 📊 Size Monitoring: Track the size of stored data
  • 🧪 Highly Tested: Test coverage over 95%

Installation

# Using npm
npm install @brushy/localstorage

# Using yarn
yarn add @brushy/localstorage

# Using pnpm
pnpm add @brushy/localstorage

Basic Usage

Simple LocalStorage

import { LocalStorage } from "@brushy/localstorage";

// Create an instance with custom prefix (optional)
const storage = new LocalStorage("@myapp:");

// Store data
storage.set("user", { name: "John", age: 30 });

// Retrieve data
const user = storage.get("user");
console.log(user); // { name: 'John', age: 30 }

// Check if a key exists
if (storage.has("user")) {
  console.log("User found!");
}

// Remove data
storage.remove("user");

// Clear all data with your prefix
storage.clear();

Advanced Options

// Store with TTL (expires after 1 hour)
storage.set("session", { token: "abc123" }, { ttl: 3600000 });

// Store with automatic compression
storage.set("largeData", bigObject, { compress: true });

// Check remaining TTL
const ttl = storage.getTTL("session");
console.log(`Session expires in ${ttl / 1000} seconds`);

// Get approximate size in bytes
const size = storage.getSize("largeData");
console.log(`Data size: ${size} bytes`);

Events and Subscriptions

// Subscribe to changes on a specific key
const unsubscribe = storage.subscribe("user", (key, newValue, oldValue) => {
  console.log(`${key} changed from`, oldValue, "to", newValue);
});

// Stop receiving notifications
unsubscribe();

JSON Storage

For working specifically with JSON data:

import { JSONStorage } from "@brushy/localstorage";

const jsonStorage = new JSONStorage("@myapp:json:");

// Store JSON data
jsonStorage.setJSON("config", { theme: "dark", fontSize: 16 });

// Retrieve JSON data
const config = jsonStorage.getJSON("config");

// Update JSON data (merging with existing)
jsonStorage.updateJSON("config", { fontSize: 18 });
// Now config = { theme: 'dark', fontSize: 18 }

// Merge arrays
jsonStorage.mergeArrays("tags", ["javascript", "typescript"]);
jsonStorage.mergeArrays("tags", ["react", "typescript"]);
// Result: ['javascript', 'typescript', 'react']

Lazy Storage

For large datasets that you want to load on demand:

import { LazyStorage } from "@brushy/localstorage";

const lazyStorage = new LazyStorage("@myapp:lazy:");

// Store data with lazy fields
const userData = {
  id: 123,
  name: "Mary",
  posts: Array(1000)
    .fill()
    .map((_, i) => ({ id: i, title: `Post ${i}` })),
  friends: Array(500)
    .fill()
    .map((_, i) => ({ id: i, name: `Friend ${i}` })),
};

lazyStorage.setLazy("user", userData, {
  lazyFields: ["posts", "friends"], // These fields will be loaded on demand
  chunkSize: 100, // Chunk size for large arrays
});

// Retrieve data (lazy fields will be loaded when accessed)
const user = lazyStorage.getLazy("user");

// Access a lazy field (automatically loaded)
console.log(user.posts.length); // 1000

// Preload specific fields
lazyStorage.preload("user", ["friends"]);

React Hooks

For use in React applications:

import {
  useStorage,
  useJSONStorage,
  useLazyStorage,
} from "@brushy/localstorage/react";

function App() {
  // Basic storage hook
  const [token, setToken, removeToken] = useStorage("auth:token", null);

  // JSON data hook
  const [settings, setSettings, updateSettings] = useJSONStorage(
    "app:settings",
    {
      theme: "light",
      notifications: true,
    },
  );

  // Lazy data hook
  const [userData, setUserData] = useLazyStorage("user:data", null, {
    lazyFields: ["posts", "comments"],
  });

  return (
    <div>
      <button onClick={() => setToken("new-token-123")}>Login</button>
      <button onClick={() => updateSettings({ theme: "dark" })}>
        Dark Mode
      </button>
      {userData && <UserProfile data={userData} />}
    </div>
  );
}

Detailed Documentation

For more detailed information about the API and advanced examples, see the complete documentation.

Additional Documentation

Other Languages

License

MIT