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.
Maintainers
Readme
💾 use-local-storage-state-react
Production-ready, zero-dependency React 18 & 19 hook for persistent state in
localStoragewith real-time cross-tab synchronization and SSR hydration safety.
✨ Features
- 🔄 Real-Time Cross-Tab Sync — Automatically listens to browser
storageevents 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 nativeReact.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 fromlocalStorageand resets state back toinitialValue.
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
