react-sync-storage
v1.0.0
Published
A lightweight React hook for persistent local storage state
Maintainers
Readme
react-sync-storage
A lightweight, zero-dependency React hook for persistent state synchronization with localStorage.
Unlike component-level state (useState), state managed by this hook survives page refreshes, browser restarts, and stays in sync across multiple open tabs in real time.
🚀 Features
- Persistent State — Data survives page refreshes and browser restarts.
- Cross-Tab Sync — Changes in one tab automatically reflect in all other open tabs, in real time, via the native
storageevent. - Type-Safe — Fully generic, works with any serializable data type (
number,string,boolean, objects, arrays). - Zero Dependencies — Keeps your bundle size minimal.
- Drop-in API — Same usage pattern as React's
useState, no learning curve.
📦 Installation
npm install react-sync-storage🔧 Usage
useSyncStorage works exactly like useState, but persists the value to localStorage and keeps it synced across tabs.
import { useSyncStorage } from "react-sync-storage";
function App() {
const [count, setCount] = useSyncStorage<number>("count", 0);
const [isLoading, setIsLoading] = useSyncStorage<boolean>("isLoading", true);
const [name, setName] = useSyncStorage<string>("name", "alex");
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Loading: {isLoading ? "Yes" : "No"}</p>
<button onClick={() => setIsLoading(!isLoading)}>Toggle Loading</button>
<p>Name: {name}</p>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}Open this page in two browser tabs side by side — update a value in one, watch it update instantly in the other.
📖 API
const [value, setValue] = useSyncStorage<T>(key: string, initialValue: T);| Parameter | Type | Description |
|----------------|----------|---------------------------------------------------|
| key | string | Unique localStorage key used to persist the value |
| initialValue | T | Default value used if no stored value exists |
Returns a tuple [value, setValue], identical shape to React's useState.
⚙️ How It Works
- On mount, the hook reads the existing value from
localStoragefor the given key (falling back toinitialValueif none exists). - On every update, the new value is serialized and written back to
localStorage. - The hook listens for the native
storageevent, so changes made in other tabs are picked up and reflected instantly — no polling, no extra libraries.
📄 License
ISC
