useSessionStorage
Manages session storage with declarative methods.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
key | string | - | The key to store the value in session storage |
initialValue | any | - | The initial value to store in session storage |
options? | UseSessionStorageOptions | - | The options for the hook |
Options
Prop | Type | Default | Description |
---|---|---|---|
serialize? | (value: any) => string | JSON.stringify | The function to serialize the value |
deserialize? | (value: string) => any | JSON.parse | The function to deserialize the value |
Key Features & Details
Cross-Tab Synchronization
- The hook listens for
storage
events and updates the state if the value changes in another tab or window (for the same session).
Serialization & Deserialization
- By default, values are serialized with
JSON.stringify
and deserialized withJSON.parse
. - You can provide custom
serialize
anddeserialize
functions for non-JSON data or advanced use cases.
Error Handling
- If reading or writing to sessionStorage fails (e.g., quota exceeded, invalid JSON), the hook logs a warning and falls back to the initial value.
SSR & Initial Value
- On the server, the hook always returns the initial value.
- The initial value is only used if there is no value in sessionStorage for the given key.
Best Practices & Caveats
- The hook is client-side only; on the server, it does not interact with sessionStorage.
- Avoid storing sensitive data in sessionStorage.
- Changing the
key
will re-read and update the value from sessionStorage. - For best performance, avoid creating new
serialize
/deserialize
functions on every render (useuseCallback
oruseMemo
if needed).
Examples
Basic Usage
const [value, setValue] = useSessionStorage('my-key', 'default');
setValue('new value');
With Custom Serialization
const [value, setValue] = useSessionStorage(
'user',
{ name: 'Alice' },
{
serialize: (v) => btoa(JSON.stringify(v)),
deserialize: (v) => JSON.parse(atob(v)),
},
);
Cross-Tab Sync
const [theme, setTheme] = useSessionStorage('theme', 'light');
// Changing theme in one tab will update it in all open tabs (for the same session)