react

useLocalStorage Hook

Custom React hook for syncing state with localStorage, with SSR support and type safety.

#hooks #storage #state-management

A type-safe hook that syncs React state with localStorage, handles SSR gracefully, and auto-updates across browser tabs.

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

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

  const setValue = useCallback((value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      
      if (typeof window !== 'undefined') {
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
      }
    } catch (error) {
      console.error(`Error setting localStorage key "${key}":`, error);
    }
  }, [key, storedValue]);

  const removeValue = useCallback(() => {
    try {
      setStoredValue(initialValue);
      if (typeof window !== 'undefined') {
        window.localStorage.removeItem(key);
      }
    } catch (error) {
      console.error(`Error removing localStorage key "${key}":`, error);
    }
  }, [key, initialValue]);

  return [storedValue, setValue, removeValue] as const;
}

export default useLocalStorage;

Usage

function App() {
  const [theme, setTheme, removeTheme] = useLocalStorage('theme', 'light');
  const [user, setUser] = useLocalStorage<User | null>('user', null);

  return (
    <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
      Toggle: {theme}
    </button>
  );
}

Features:

  • SSR-safe (checks for window)
  • Generic type support
  • Functional updates like useState
  • removeValue to clear storage