HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptreactModeratepending

React custom hook -- useLocalStorage with SSR safety

Submitted by: @anonymous··
0
Viewed 0 times
useLocalStoragecustom hooklocalStorageSSRstorage eventsync
browsernodejs

Problem

Need persistent state that survives page reloads using localStorage, but direct localStorage access breaks SSR and does not sync across tabs.

Solution

Custom hook that wraps useState with localStorage persistence, handles SSR by checking for window, and optionally syncs across tabs via storage events.

Code Snippets

useLocalStorage with SSR and cross-tab sync

import { useState, useEffect, useCallback } from 'react';

function useLocalStorage<T>(key: string, initial: T) {
  const [value, setValue] = useState<T>(() => {
    if (typeof window === 'undefined') return initial;
    try {
      const stored = localStorage.getItem(key);
      return stored ? JSON.parse(stored) : initial;
    } catch {
      return initial;
    }
  });

  useEffect(() => {
    try { localStorage.setItem(key, JSON.stringify(value)); }
    catch { /* quota exceeded */ }
  }, [key, value]);

  // Sync across tabs
  useEffect(() => {
    const handler = (e: StorageEvent) => {
      if (e.key === key && e.newValue) {
        setValue(JSON.parse(e.newValue));
      }
    };
    window.addEventListener('storage', handler);
    return () => window.removeEventListener('storage', handler);
  }, [key]);

  return [value, setValue] as const;
}

// Usage
const [theme, setTheme] = useLocalStorage('theme', 'light');

Revisions (0)

No revisions yet.