h3/use's logo

h3/use

Command Palette

Search for a command to run...

useSessionStorage

Manages session storage with declarative methods.

useSessionStorage
This component uses the useSessionStorage hook to manage a session storage item.
{"name":"","age":0}

Installation

Props

PropTypeDefaultDescription
keystring-The key to store the value in session storage
initialValueany-The initial value to store in session storage
options?UseSessionStorageOptions-The options for the hook

Options

PropTypeDefaultDescription
serialize?(value: any) => stringJSON.stringifyThe function to serialize the value
deserialize?(value: string) => anyJSON.parseThe 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 with JSON.parse.
  • You can provide custom serialize and deserialize 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 (use useCallback or useMemo 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)