A React hook built on top of useSyncExternalStore that synchronizes state with localStorage, providing reactive updates across browser tabs and windows.
Key Features
- Cross-tab synchronization: Changes in one tab automatically update all other tabs
- Infinite loop prevention: Uses string snapshots internally to prevent React re-render loops
- Automatic cleanup: Setting
null,undefined, or""removes the item from localStorage - Error handling: Falls back to
initialValueif JSON parsing fails
Important Limitations
- No SSR support: This hook must only be called on the client side. The server snapshot
always returns
null, which will cause the initial value to be used during hydration. - JSON serialization: Only values that can be serialized with
JSON.stringify()are supported. Functions,undefined, and circular references cannot be stored.
How it works
- Uses
useSyncExternalStoreto subscribe to localStorage changes - Listens to native
storageevents (for changes from other tabs) - Dispatches custom
local-storage-changeevents (for changes in the current tab) - Returns a string snapshot to prevent infinite loops, then parses it in a
useMemo
Don't refactor this hook blindly
Be careful with useSyncExternalStore. The store snapshot returned by getSnapshot must be immutable. learn more
Installation
Usage
import { useLocalStorage } from "@/src/hooks/useLocalStorage";
const [value, setValue] = useLocalStorage("key", "default value");