-
Notifications
You must be signed in to change notification settings - Fork 0
useLocalStorage
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
Synchronizes state with localStorage so it persists across browser reloads. Automatically parses JSON and updates state when storage events fire from other tabs.
The simplest possible implementation, passing a key and an initial fallback value.
import { useLocalStorage } from 'react-hook-lab';
function BasicTheme() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return (
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle {theme}
</button>
);
}Storing complex objects. The hook automatically handles JSON.stringify and JSON.parse.
import { useLocalStorage } from 'react-hook-lab';
function UserSettings() {
const [settings, setSettings] = useLocalStorage('user_settings', { notifications: true, autoSave: false });
const toggleNotifications = () => {
setSettings({ ...settings, notifications: !settings.notifications });
};
return (
<div>
<label>
<input type="checkbox" checked={settings.notifications} onChange={toggleNotifications} />
Enable Notifications
</label>
</div>
);
}An exhaustive example demonstrating cross-tab synchronization. (Note: Because this hook listens to the storage event, if you change activeTab in one browser window, it will instantly update in another).
import { useLocalStorage } from 'react-hook-lab';
function MultiWindowSync() {
const [activeTab, setActiveTab] = useLocalStorage('active_dashboard_tab', 0);
return (
<div>
<p>Open this page in two browser tabs. Clicking below syncs them instantly.</p>
<button onClick={() => setActiveTab(0)} style={{ fontWeight: activeTab === 0 ? 'bold' : 'normal' }}>Tab 1</button>
<button onClick={() => setActiveTab(1)} style={{ fontWeight: activeTab === 1 ? 'bold' : 'normal' }}>Tab 2</button>
</div>
);
}-
key(Required)- Type:
string - Description: The exact string key used to save and retrieve the value from
window.localStorage.
- Type:
-
initialValue(Required)- Type:
T - Description: The fallback value to return and save if the
keydoes not already exist inlocalStorage, or iflocalStorageis disabled.
- Type:
Returns readonly [T, (newValue: T) => void]:
-
value: The parsed value from localStorage, or theinitialValue. -
setStoredValue: A state setter function that updates the React state AND synchronously writes the stringified value back tolocalStorage.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM