typescriptadvanced
useStorageEvent Hook
Syncs state across browser tabs by listening to localStorage storage events.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useState, useEffect, useCallback } from 'react';
export function useCrossTabState<T>(key: string, initialValue: T): [T, (value: T) => void] {
const [state, setState] = useState<T>(() => {
try {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
const setValue = useCallback((value: T) => {
setState(value);
localStorage.setItem(key, JSON.stringify(value));
}, [key]);
useEffect(() => {
const handler = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
try {
setState(JSON.parse(e.newValue));
} catch { /* ignore */ }
}
};
window.addEventListener('storage', handler);
return () => window.removeEventListener('storage', handler);
}, [key]);
return [state, setValue];
}
// Usage:
// const [theme, setTheme] = useCrossTabState('theme', 'dark');
// Changes in one tab will sync to all other tabs.Use Cases
- Theme sync across tabs
- Auth state sync
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptadvanced
useIndexedDB Hook
Simple IndexedDB wrapper hook for persistent client-side storage with get, set, and delete.
Best for: Offline data storage
#hooks#indexeddb
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage