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-local-storage-state-react

v1.0.0

Published

Production-ready React 18 & 19 hook for persistent state in localStorage with cross-tab sync and SSR hydration safety.

Readme

💾 use-local-storage-state-react

Production-ready, zero-dependency React 18 & 19 hook for persistent state in localStorage with real-time cross-tab synchronization and SSR hydration safety.

npm version License: MIT Sponsor React 18 & 19 TypeScript


✨ Features

  • 🔄 Real-Time Cross-Tab Sync — Automatically listens to browser storage events so multiple open tabs stay in sync without page reloads.
  • 🛡️ SSR & Incognito Safe — Gracefully uses initial state fallback if window, localStorage, or quota is unavailable during server rendering.
  • ⚡ Zero Dependencies — Less than 1 KB minified, pure native TypeScript.
  • 🔒 Type-Safe Generics — Full state inference: const [user, setUser] = useLocalStorage<User>('user', initial).
  • 🧰 Functional State Updates — Supports updater functions setCount(prev => prev + 1) exactly like native React.useState().
  • 📦 Dual ESM & CommonJS — Compatible with Next.js (App & Pages Router), Vite, Remix, Gatsby, and React Native Web.

📥 Installation

# npm
npm install use-local-storage-state-react

# pnpm
pnpm add use-local-storage-state-react

# yarn
yarn add use-local-storage-state-react

# bun
bun add use-local-storage-state-react

🚀 Usage & Real-World Examples

1. Theme Selector with Cross-Tab Sync

When a user switches to dark mode in one tab, all other tabs update instantly:

import React from 'react';
import { useLocalStorage } from 'use-local-storage-state-react';

export function ThemeToggle() {
  const [theme, setTheme] = useLocalStorage<'light' | 'dark'>('app_theme', 'light');

  const toggle = () => {
    setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
  };

  return (
    <button onClick={toggle} className={`theme-${theme}`}>
      Current Theme: {theme} (Click to switch)
    </button>
  );
}

2. Complex Objects (User Profile & Settings)

import React from 'react';
import { useLocalStorage } from 'use-local-storage-state-react';

interface UserSettings {
  volume: number;
  notifications: boolean;
  language: string;
}

const defaultSettings: UserSettings = {
  volume: 80,
  notifications: true,
  language: 'en',
};

export function SettingsPanel() {
  const [settings, setSettings, resetSettings] = useLocalStorage<UserSettings>(
    'user_settings',
    defaultSettings
  );

  const toggleNotifications = () => {
    setSettings((prev) => ({
      ...prev,
      notifications: !prev.notifications,
    }));
  };

  return (
    <div>
      <h3>Audio Volume: {settings.volume}%</h3>
      <label>
        <input
          type="checkbox"
          checked={settings.notifications}
          onChange={toggleNotifications}
        />
        Enable Notifications
      </label>
      <button onClick={resetSettings}>Reset to Defaults</button>
    </div>
  );
}

3. Reading Outside React Lifecycles (getLocalStorageValue)

If you need to read an entry in an API service or router guard before React mounts:

import { getLocalStorageValue } from 'use-local-storage-state-react';

interface AuthSession {
  token: string;
  expiresAt: number;
}

// Safely reads value without throwing during SSR:
const session = getLocalStorageValue<AuthSession | null>('auth_session', null);

if (session && session.expiresAt > Date.now()) {
  console.log('User has active token:', session.token);
}

📖 API Reference

useLocalStorage<T>(key, initialValue, options?)

| Parameter | Type | Default | Description | |---|---|---|---| | key | string | Required | Storage key name | | initialValue | T \| (() => T) | Required | Default value used if key does not exist or during SSR | | options | UseLocalStorageOptions<T> | {} | Custom serialization and sync controls |

Return Value Tuple:

[value, setValue, removeValue]

  • value: The current stored state (T).
  • setValue: Setter accepting value or functional updater (prev: T) => T.
  • removeValue: Removes the item from localStorage and resets state back to initialValue.

UseLocalStorageOptions<T>:

| Option | Type | Default | Description | |---|---|---|---| | serializer | (val: T) => string | JSON.stringify | Custom string serializer | | deserializer | (str: string) => T | JSON.parse | Custom string deserializer | | syncCrossTab | boolean | true | Whether to listen to storage events across browser tabs |


💖 Support the Project

If use-local-storage-state-react simplified state persistence in your web applications, please consider sponsoring:

👉 Sponsor @Piratha97 on GitHub Sponsors


📄 License

MIT © 2026 Pirapaakaran Pirathapan