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
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
Full Signature
Parameters
(valueTdeserializer?functiondefault:JSON.parse
Custom deserializer function
Full Signature
Parameters
(valuestringinitializeWithValue?uniondefault:true
Read from storage immediately on initial client render
Full Signature
onError?function
Callback invoked when reading, writing, or parsing storage throws an error
Full Signature
Parameters
(errorunknown