useLocalStorage: Persistent localStorage State for React
Persist typed state in localStorage with JSON serialization, a useState-compatible API, automatic cross-tab sync via storage events, and error handling.
Use this file to discover all available pages before exploring further.
useLocalStorage is a React hook that provides a useState-style interface for persisting values in the browser’s localStorage. It handles JSON serialization and deserialization automatically, keeps state in sync across multiple tabs via the storage event, and exposes a third tuple element to remove the stored value and reset to the initial state. It accepts custom serializers for complex types like Date objects, an onError callback for graceful failure handling, and an initializeWithValue flag to control server-side rendering behaviour.
When true (the default), the hook reads from localStorage during the initial render. Set to false to start with initialValue and hydrate from localStorage in an effect — useful for SSR environments to avoid hydration mismatches.
A setter function with the same API as React’s useState setter. Accepts a new value directly or an updater function (prev: T) => T. Updates both the React state and localStorage atomically.
Changes from other browser tabs are detected via the storage event and automatically reflected in the hook’s state, keeping all open tabs in sync.
The hook guards against environments where window.localStorage is unavailable (SSR, private browsing that has blocked storage) and calls onError gracefully rather than throwing.
The setValue setter accepts an updater function (prev) => next just like useState, making it easy to merge partial updates into object values.
If you need session-scoped persistence (cleared when the tab closes), use useSessionStorage instead, which has an identical API.