@mdus/use-localstorage-hook
v2.0.7
Published
React hook to manage localStorage state with sync, reactivity, and cross-tab updates.
Maintainers
Readme
@mdus/use-localstorage-hook
A robust, zero-dependency React hook to manage localStorage state with cross-tab synchronization and reactivity.
✨ Features
- 🔄 Cross-Tab Synchronization: Instantly updates state across different browser tabs/windows using the native
storageevent listener. - 🛡️ Robust Error Handling: Wrapped in safe
try/catchblocks to prevent app crashes iflocalStorageis disabled, full, or corrupted. - ⚡ Reactive: Behaves just like
useState. Updates trigger immediate re-renders. - 🔢 Auto-Serialization: Automatically handles
JSON.stringifyon writes andJSON.parseon reads. - 🧹 Clean API: Provides intuitive helpers like
removeStoreandclearAllStore. - 📦 Zero Dependencies: Lightweight and focused.
📦 Installation
Install the package via your preferred package manager:
# npm
npm install @mdus/use-localstorage-hook
# yarn
yarn add @mdus/use-localstorage-hook
# pnpm
pnpm add @mdus/use-localstorage-hook💻 Quick Start
Here is a simple example of how to persist a user's theme preference.
import React from 'react';
import useLocalstorage from '@mdus/use-localstorage-hook';
const ThemeSwitcher = () => {
// Initialize storage with a key and a default value
const { getStore, setStore, removeStore } = useLocalstorage('app-theme', 'light');
const toggleTheme = () => {
const newTheme = getStore === 'light' ? 'dark' : 'light';
setStore(newTheme);
};
return (
<div style={{ background: getStore === 'light' ? '#fff' : '#333', padding: '20px' }}>
<h1>Current Theme: {getStore}</h1>
<button onClick={toggleTheme}>
Toggle Theme
</button>
<button onClick={removeStore} style={{ marginLeft: '10px' }}>
Reset to System Default (Remove Key)
</button>
</div>
);
};
export default ThemeSwitcher;📖 API Reference
useLocalstorage(storeName, initialData)
Parameters
| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| storeName | string | Yes | The unique key used to store data in localStorage. |
| initialData | any | Yes | The default value to use if the key does not exist yet. |
Note: If
storeNameorinitialDataare missing, the hook will throw an error to prevent silent failures.
Return Object
The hook returns an object containing the current state and utility functions:
| Property | Type | Description |
| :--- | :--- | :--- |
| getStore | any | The current value of the storage item. Acts like the state variable in useState. |
| setStore | (data: any) => void | Updates the state and persists it to localStorage. Accepts any JSON-serializable data. |
| removeStore | () => void | Removes the specific key from localStorage and resets state to null. |
| clearAllStore | () => void | Caution: Clears all data in localStorage for the domain. |
🛠 Under the Hood
Safety & Error Boundaries
Directly accessing localStorage can be dangerous in modern web development (e.g., inside Iframes, Incognito mode, or when quotas are exceeded).
This hook wraps all storage operations in try/catch blocks. If an error occurs (like a JSON parse error), it logs the issue to the console gracefully and falls back to your initialData or null, ensuring your React app doesn't crash.
Cross-Tab Reactivity
The hook attaches an event listener to the window's storage event.
- When Tab A updates the key
'user_data', the browser fires an event. - Tab B catches this event, parses the new value, and updates its local React state immediately.
- This ensures all open tabs stay in perfect sync without a page reload.
