Skip to content

useLocalStorage

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useLocalStorage

Synchronizes state with localStorage so it persists across browser reloads. Automatically parses JSON and updates state when storage events fire from other tabs.

Usage Examples

Basic (Minimum Parameters)

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>
  );
}

Common (Standard Usage)

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>
  );
}

Advanced (All Parameters)

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>
  );
}

API Reference

Parameters

  • key (Required)
    • Type: string
    • Description: The exact string key used to save and retrieve the value from window.localStorage.
  • initialValue (Required)
    • Type: T
    • Description: The fallback value to return and save if the key does not already exist in localStorage, or if localStorage is disabled.

Return Object

Returns readonly [T, (newValue: T) => void]:

  • value: The parsed value from localStorage, or the initialValue.
  • setStoredValue: A state setter function that updates the React state AND synchronously writes the stringified value back to localStorage.

Clone this wiki locally