useLocalStorage

React hook for syncing state with localStorage. Works across tabs, SSR-safe, TypeScript-ready.

Overview

useLocalStorage is a powerful React hook that synchronizes state with the browser's localStorage. It handles the complexities of SSR, provides full TypeScript generic support, and ensures your state stays in sync across multiple browser tabs automatically.

Demo

Interactive Preview

useLocalStorage

Persist state to local storage with automatic serialization and cross-tab sync.

Drawing Canvas
0 strokes cached

Open another tab to see real-time sync

API Reference

function useLocalStorage<T>(
  key: string, 
  initialValue: T
): [T, (val: T | ((prev: T) => T)) => void, () => void]

Parameters

NameTypeDescription
keystringThe unique key to store the value under in localStorage
initialValueTThe default value to use if no value is found in storage

Returns

IndexTypeDescription
[0]TThe current value (starts with initialValue or stored value)
[1](value: T | (prev: T) => T) => voidSetter function that updates state and storage
[2]() => voidClear function that resets to initialValue and removes from storage

Usage Examples

Basic Implementation

import { useLocalStorage } from 'react-hooks-ts'
 
function Profile() {
  const [name, setName] = useLocalStorage('user-name', 'Anonymous')
 
  return (
    <input 
      value={name} 
      onChange={(e) => setName(e.target.value)} 
    />
  )
}

Complex Objects

const [user, setUser, clearUser] = useLocalStorage('session', {
  id: 1,
  theme: 'dark',
  preferences: { notifications: true }
})

Features

  • SSR Safe - Prevents hydration mismatches in Next.js
  • 🔄 Cross-tab Sync - Real-time updates across multiple windows
  • 🧩 TypeScript - Full type safety for your stored data
  • JSON Handling - Automatic serialization and deserialization
  • 🛡️ Fail-Safe - Graceful error handling for corrupted data