typescriptadvanced

useStorageEvent Hook

Syncs state across browser tabs by listening to localStorage storage events.

typescript
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.