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

complete-react-storage

v0.0.2

Published

Hook para sincronizar estado con localStorage/sessionStorage con TTL y cross-tab

Readme

complete-react-storage

npm bundlephobia types tree-shaking

Hook para sincronizar estado con localStorage / sessionStorage (TTL, cross‑tab).

🚀 Instalación

npm install complete-react-storage
# o
pnpm add complete-react-storage
# o
yarn add complete-react-storage

📖 Uso básico

import { useStorage } from 'complete-react-storage';

function MyComponent() {
  const [count, setCount, removeCount] = useStorage('counter', 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>+</button>
      <button onClick={() => setCount(c => c - 1)}>-</button>
      <button onClick={removeCount}>Reset</button>
    </div>
  );
}

🔧 API

useStorage(key, initial, options?)

Retorna una tupla [value, setValue, removeValue]:

  • value: Valor actual del storage
  • setValue: Función para actualizar el valor (acepta función callback)
  • removeValue: Función para eliminar del storage y resetear al valor inicial

Parámetros

| Parámetro | Tipo | Descripción | | --------- | ---------------------- | ------------------------------------- | | key | string | Clave única para el storage | | initial | T | Valor inicial si no existe en storage | | options | UseStorageOptions<T> | Opciones de configuración |

Opciones

| Propiedad | Tipo | Default | Descripción | | ---------- | ---------------------- | ----------- | ------------------------------ | | area | "local" \| "session" | "local" | Tipo de storage a usar | | json | boolean | true | Si usar JSON.stringify/parse | | ttl | number | undefined | Tiempo de vida en milisegundos | | crossTab | boolean | true | Sincronización entre pestañas | | migrate | (raw: unknown) => T | undefined | Función de migración de datos |

📋 Ejemplos

Con TTL (Time To Live)

const [token, setToken, clearToken] = useStorage('auth-token', null, {
  ttl: 1000 * 60 * 60 * 24, // 24 horas
  area: 'session'
});

// El token se elimina automáticamente después de 24 horas

Datos complejos

interface User {
  id: number;
  name: string;
  email: string;
}

const [user, setUser, clearUser] = useStorage<User | null>('user', null, {
  crossTab: true,
  area: 'local'
});

// Actualizar usuario
setUser(current => current ? { ...current, name: 'Nuevo nombre' } : null);

Con migración de datos

const [settings, setSettings] = useStorage('app-settings', { theme: 'light' }, {
  migrate: (raw) => {
    // Migrar datos de versiones anteriores
    if (typeof raw === 'string') {
      return { theme: raw }; // v1 solo guardaba el tema como string
    }
    return raw as any;
  }
});

SessionStorage sin JSON

const [sessionId, setSessionId] = useStorage('session', '', {
  area: 'session',
  json: false, // Almacenar como string plano
  crossTab: false
});

Configuración avanzada

const [cache, setCache, clearCache] = useStorage('api-cache', {}, {
  area: 'local',
  ttl: 1000 * 60 * 5, // 5 minutos
  crossTab: true,
  migrate: (raw) => {
    // Limpiar cache legacy
    if (!raw || typeof raw !== 'object') return {};
    return raw;
  }
});

✨ Características

  • SSR Safe: Funciona en servidor sin errores
  • TypeScript: Tipado completo incluido
  • TTL Support: Expiración automática de datos
  • Cross-tab: Sincronización entre pestañas/ventanas
  • Migration: Función para migrar datos legacy
  • Error Handling: Manejo robusto de errores
  • Fallback: Funciona sin storage disponible
  • Tree-shakeable: Solo importa lo que usas
  • Minimalista: < 2KB gzipped

🌐 Compatibilidad

  • React ≥18
  • Navegadores con localStorage/sessionStorage
  • Fallback automático cuando storage no está disponible
  • Compatible con modo privado de Safari

💡 Casos de uso

  • 🔐 Autenticación: Tokens con expiración automática
  • ⚙️ Configuración: Preferencias de usuario persistentes
  • 📊 Cache: Datos de API con TTL
  • 🎨 Temas: Dark/light mode sincronizado
  • 📝 Formularios: Guardar borrador automáticamente
  • 🛒 Carrito: E-commerce state persistence

🔗 Recursos adicionales