Skip to Content
ohooks

useLocalStorage

Persists and synchronizes state with window.localStorage across components and browser tabs.

Loading preview...

The useLocalStorage hook synchronizes React state with window.localStorage using useSyncExternalStore, automatically updating all subscribed components in the current tab as well as across other open tabs via the storage event.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useLocalStorage.json

Usage

Examples

Persisting Complex Objects

Objects and arrays are serialized with JSON.stringify and parsed with JSON.parse by default, and the setter supports functional updates just like useState.

Custom Serializer and Error Handling

Provide custom serializer, deserializer, and onError callbacks when storing non-JSON types such as Date or Set.

API Reference

StorageOptions

Configuration options for custom serialization, cross-tab sync, and error handling.

Property
Specification
serializer?
functiondefault:JSON.stringify
Custom serializer function
deserializer?
functiondefault:JSON.parse
Custom deserializer function
initializeWithValue?
uniondefault:true
Read from storage immediately on initial client render
onError?
function
Callback invoked when reading, writing, or parsing storage throws an error