Sync localStorage Values Across Tabs in React
To reflect a value saved in localStorage immediately in other tabs open on the same site, subscribe to the browser's storage event with useSyncExternalStore. This works well for display settings like font size or dark mode: when you change one tab, you want the other open tabs to show the same thing.
However, the storage event is not delivered to the tab that made the change. The hook in this article notifies its own tab directly and receives changes from other tabs through the storage event. In a test environment, I opened two tabs and confirmed that the values stay in sync, under which conditions the event is delivered, and what goes wrong with the mistaken approaches.
The test environment was Ubuntu 24.04, Node.js 22.23.4, React / react-dom 19.3.1, and TypeScript 7.0.2. I type-checked the code with tsc, bundled it with esbuild, and opened the development build wrapped in StrictMode, operating Chromium 153 through Playwright 1.63.0. The two tabs were two pages opened in the same Playwright browser context. The two examples of wrong code were opened without StrictMode. I did not test Firefox, Safari, mobile browsers, cases that span separate windows or browser profiles, or behavior on top of frameworks such as Next.js.

- 1. The storage event reaches only other tabs
- 2. A hook that reads localStorage
- 3. Without notifying your own tab, the display does not change when you click
- 4. Calling JSON.parse inside getSnapshot causes an infinite loop
- 5. Keep the screen working when the value is broken or a save fails
- 6. When rendering on the server, the default value appears first
The storage event reaches only other tabs
According to MDN's storage event page, this event fires when another tab on the same origin changes localStorage. It does not fire in the tab that made the change.
In my test environment, when I changed a value in tab A, the event reached tab B only, and tab A received nothing. The event tab B received was:
B に届いたイベント [
{
key: 'settings',
oldValue: null,
newValue: '{"fontSize":18,"compact":false}',
area: 'local'
}
]
Whether the event fired, and what key and newValue contained, depended on how the change was made. All of this follows the setItem() and related steps in the HTML specification.
| What tab A did | Event received by tab B |
|---|---|
Changed a value with setItem() |
key is the changed key, newValue is the new value |
Called setItem() with the same value as now |
Not fired |
Deleted a value with removeItem() |
newValue is null |
Removed everything with clear() |
key, oldValue, and newValue are all null |
| Wrote to sessionStorage | Not fired |
With clear(), key is null. So if you write the condition as "re-read only when e.key === key," you will miss the case where everything was cleared. The hook in this article does not filter by key. When an event arrives, it re-reads from localStorage. I explain below why it does not re-render when the value is unchanged.
A hook that reads localStorage
Here is the whole hook. Values are stored as JSON.
import { useCallback, useMemo, useSyncExternalStore } from 'react';
// The party to notify that it was rewritten within the same tab
const listeners = new Set<() => void>();
function subscribe(listener: () => void) {
listeners.add(listener);
// When it is rewritten in another tab, a storage event is delivered
const onStorage = (e: StorageEvent) => {
if (e.storageArea === localStorage) listener();
};
window.addEventListener('storage', onStorage);
return () => {
listeners.delete(listener);
window.removeEventListener('storage', onStorage);
};
}
function notify() {
for (const l of listeners) l();
}
function readRaw(key: string): string | null {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
export function useLocalStorage<T>(key: string, initial: T) {
// The snapshot is returned as a string (if the value is the same each time, do not redraw)
const raw = useSyncExternalStore(
subscribe,
() => readRaw(key),
() => null,
);
const value = useMemo<T>(() => {
if (raw === null) return initial;
try {
return JSON.parse(raw) as T;
} catch {
return initial;
}
// It is assumed that initial is a value that does not change (such as a module constant)
}, [raw]);
const setValue = useCallback(
(next: T) => {
try {
localStorage.setItem(key, JSON.stringify(next));
} catch {
// Could not be saved due to insufficient capacity, etc.
}
// Storage events are not delivered to one's own tab, so notify it yourself
notify();
},
[key],
);
const remove = useCallback(() => {
try {
localStorage.removeItem(key);
} catch {
// localStorage is not available
}
notify();
}, [key]);
return [value, setValue, remove] as const;
}
useSyncExternalStore takes a subscribe function and a function that returns the current value (getSnapshot). The official reference also has an example that subscribes to a browser API such as navigator.onLine, whose value changes and is announced through events.
subscribe registers the function React passes in on two sources: the storage event, which carries changes from other tabs, and the listeners set, which carries changes from the same tab. setValue and remove write to localStorage and then call notify() to inform components in the same tab. subscribe is defined outside the component. According to the official reference, if you pass a different subscribe on each render, React resubscribes every time.
The condition e.storageArea === localStorage ignores changes to sessionStorage. According to MDN, if the same tab contains a same-origin iframe, a storage event can also fire when that iframe changes its sessionStorage.
Components use the hook much like useState. Two components in the same tab that read the same key always get the same value.
type Settings = { fontSize: number; compact: boolean };
const DEFAULT: Settings = { fontSize: 16, compact: false };
function SettingsPanel() {
const [settings, setSettings, reset] = useLocalStorage<Settings>('settings', DEFAULT);
return (
<section>
<p>文字の大きさ:{settings.fontSize}px</p>
<button onClick={() => setSettings({ ...settings, fontSize: settings.fontSize + 2 })}>大きく</button>
<label>
<input
type="checkbox"
checked={settings.compact}
onChange={(e) => setSettings({ ...settings, compact: e.target.checked })}
/>
詰めて表示する
</label>
<button onClick={reset}>元に戻す</button>
</section>
);
}
function Preview() {
const [settings] = useLocalStorage<Settings>('settings', DEFAULT);
return (
<p style={{ fontSize: settings.fontSize, lineHeight: settings.compact ? 1.2 : 1.8 }}>
見本の文章です。
</p>
);
}
The code I tested also had a heading and a "Smaller" button, which are omitted here. I opened two tabs. When I pressed "Larger" in tab A, SettingsPanel and Preview both showed 18px in tab A and in tab B. When I checked the compact checkbox in tab B, the event reached only tab A, and the checkbox in tab A became checked too. Pressing the reset button returned both tabs to the default 16px.
Changes made without going through the hook are not reflected in the same tab. With the value at 20px, I ran localStorage.clear() directly in tab A's page. Tab B went back to 16px, but tab A stayed at 20px. As MDN describes, tab A does not receive a storage event, and notify() is not called, so nothing updated tab A.
Without notifying your own tab, the display does not change when you click
If you subscribe only to the storage event and do not call notify() after writing, the tab where you made the change does not update. I tested this with the following code.
function subscribe(listener: () => void) {
window.addEventListener('storage', listener);
return () => window.removeEventListener('storage', listener);
}
function App() {
const raw = useSyncExternalStore(subscribe, () => localStorage.getItem('count'));
const count = Number(raw ?? '0');
return (
<>
<output>{count}</output>
<button onClick={() => localStorage.setItem('count', String(count + 1))}>増やす</button>
</>
);
}
These are the results of pressing the increment button three times in tab A.
タブAで1回目のクリック: A の表示=0 A の保存値=1 B の表示=1
タブAで2回目のクリック: A の表示=0 A の保存値=1 B の表示=1
タブAで3回目のクリック: A の表示=0 A の保存値=1 B の表示=1
Tab B received the storage event and showed 1. Tab A, where the click happened, was not re-rendered and stayed at 0. Because the count used for rendering was still 0, every click wrote the same 1, so the stored value never went past 1.
Calling JSON.parse inside getSnapshot causes an infinite loop
When you store an object, it is tempting to call JSON.parse inside getSnapshot and return the object. But this does not work.
// Mistake: JSON.parse runs on every read, so a new object is created each time
function getSnapshot() {
return JSON.parse(localStorage.getItem('settings') ?? '{"fontSize":16}') as { fontSize: number };
}
When I opened this in the test environment, nothing was displayed, and the console showed the following errors.
The result of getSnapshot should be cached to avoid an infinite loop
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
As the official reference explains in its section on this error, React re-renders when the value returned by getSnapshot differs from the previous one. JSON.parse creates a new object on every call, so React treats the value as changed every time, even when the content is the same.
In the hook in this article, getSnapshot returns the string from localStorage as is, and JSON.parse runs inside useMemo. According to the official reference, React compares the return values of getSnapshot with Object.is and does not re-render if they match. Identical strings are Object.is equal, so when an event arrives because a different key changed in another tab, this component does not re-render.
Return the localStorage string (or null) from getSnapshot as is. Convert it to an object only when the string has changed.
Keep the screen working when the value is broken or a save fails
A value in localStorage may have been written by another tab or by older code. In the test environment, I set tab A to 20px and then wrote '{broken', which is not valid JSON. Tab B caught the JSON.parse failure, showed the default 16px, and logged no errors to the console.
Writes can also fail. The specification says that setItem() throws QuotaExceededError when a value cannot be stored. In the test environment, calling setItem() with a 6MB string in Chromium threw QuotaExceededError. The setValue in this hook wraps setItem() in try/catch, so a failed save does not throw out of the click handler, and execution continues to notify().
When rendering on the server, the default value appears first
The third argument to useSyncExternalStore, getServerSnapshot, is used when rendering on the server and when hydrating that HTML in the browser (official reference). The server has no localStorage, so this hook returns null there and renders the default value.
In the test environment, I opened HTML generated with renderToString in a tab where 24px was saved in localStorage. The HTML, before JavaScript ran, showed 16px, and after hydration it changed to 24px. The console showed no hydration mismatch errors. Until hydration finishes, the default 16px is displayed, not the saved value.





