A React hook built on top of useSyncExternalStore for managing state with sessionStorage.
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 sessionStorage changes - Dispatches custom
session-storage-changeevents - Returns a string snapshot to prevent infinite loops, then parses it in a
useMemo
Installation
Usage
import { useSessionStorage } from "@/src/hooks/useSessionStorage";
const [value, setValue] = useSessionStorage("key", "default value");