Typed HooksGetting StarteduseLocalStorage

useLocalStorage

A React hook for managing localStorage with automatic JSON serialization, type safety, and cross-tab synchronization.

⚠️ This content is not available in your language yet.

useLocalStorage is a powerful React hook that provides a seamless interface for managing browser localStorage with full TypeScript support. It automatically handles JSON serialization/deserialization, provides type safety, and includes cross-tab synchronization to keep data consistent across multiple browser tabs.

The hook supports complex data types including objects, arrays, and primitive values. It also provides custom serialization options for advanced use cases like Date objects, includes error handling capabilities, and automatically syncs changes across browser tabs using the storage event. This hook uses our own custom hook useEventListener to listen for storage changes across tabs.

A simple example demonstrating primitive value storage with automatic persistence:

Persistent Counter
0
const [value, setValue, removeValue] = useLocalStorage(key, initialValue)
Refresh the page to see values persist across sessions

This example shows how to store and manage basic data types like numbers and strings. The counter persists across page refreshes, and the name input maintains its value even when navigating away and back.

Installation

pnpm dlx shadcn@latest add https://shaddy-docs.vercel.app/r/use-local-storage

Store Complex Objects with Automatic Serialization

Complex object storage with nested properties and automatic serialization:

User Preferences

Saved Locally
Current Settings:
{
  "theme": "light",
  "notifications": true,
  "language": "en",
  "autoSave": false,
  "fontSize": 14
}
useLocalStorage('user-settings', defaultObject)
Complex objects are automatically serialized/deserialized

This example demonstrates storing complex objects with multiple properties. The settings object is automatically serialized to JSON and stored in localStorage, with all changes immediately persisted and synchronized across tabs.

Form Draft Auto-Save

Automatic form data persistence to prevent data loss during editing:

Draft Article

Auto-saves form data as you type - try refreshing the page!

This example shows how to implement auto-save functionality for forms. As users type, their input is automatically saved to localStorage, preventing data loss if they accidentally close the tab or refresh the page.

Advanced Features with Custom Serialization

Custom serialization for complex data types and multiple storage patterns:

Advanced Features

Custom Date Serialization

Last Visit:
8/14/2025, 11:38:11 PM

Shopping Cart

Items: 0$0.00

This advanced example demonstrates custom serialization for Date objects and managing arrays of complex objects like a shopping cart. It shows how to handle data types that don't serialize well with JSON by default.

API

useLocalStorage<T>(key, initialValue?, options?): [T, Dispatch<SetStateAction<T>>, () => void]

Parameters

ParameterTypeDescription
keystringThe localStorage key to store the value under
initialValueT | (() => T) | undefinedThe initial value or a function to compute it. Defaults to undefined
optionsUseLocalStorageOptions<T> | undefinedOptional configuration for serialization, initialization, and error handling

Options

The options parameter provides advanced configuration:

PropertyTypeDefaultDescription
serializer(value: T) => string | undefinedJSON.stringifyCustom function to serialize the value before storing in localStorage
deserializer(value: string) => T | undefinedJSON.parseCustom function to deserialize the value when reading from localStorage
initializeWithValueboolean | undefinedtrueWhether to initialize with value from localStorage on mount
onError(error: Error, key: string) => void | undefinedConsole warningError handler called when localStorage operations fail

Returns

Returns a tuple with three elements:

IndexTypeDescription
0TThe current value from localStorage or the initial value
1Dispatch<SetStateAction<T>>A setter function that accepts a value or updater function (same API as useState)
2() => voidA function to remove the item from localStorage and reset to initial value

Types

type UseLocalStorageOptions<T> = {
  serializer?: (value: T) => string
  deserializer?: (value: string) => T
  initializeWithValue?: boolean
  onError?: (error: Error, key: string) => void
}