useLocalStorage in React

From the React Custom Hooks cheat sheet · Browser & Storage Hooks · verified Jul 2026

useLocalStorage

State that persists to localStorage with cross-tab sync

jsx
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 raw = localStorage.getItem(key)
      return raw ? (JSON.parse(raw) as T) : initial
    } catch {
      return initial
    }
  })

  useEffect(() => {
    try {
      localStorage.setItem(key, JSON.stringify(value))
    } catch {}
  }, [key, value])

  return [value, setValue] as const
}

// Usage
const [theme, setTheme] = useLocalStorage('theme', 'light')
💡 Lazy init reads from localStorage once - no re-parse on every render
📌 The `storage` event fires in OTHER tabs only - gives you cross-tab sync
⚠️ Guard for SSR (typeof window) - Next.js will crash without it
🎯 Wrap in try/catch - quota errors and private mode both throw
storagestatepersistence

More React tasks

Back to the full React Custom Hooks cheat sheet