Typed HooksGetting StarteduseSessionStorage

useSessionStorage

A React hook for managing sessionStorage with automatic JSON serialization, type safety, and cross-tab synchronization.

useSessionStorage is a powerful React hook that provides a seamless interface for managing browser sessionStorage with full TypeScript support. It automatically handles JSON serialization/deserialization, provides type safety, and includes cross-tab synchronization to keep data consistent across multiple browser tabs.

The hook supports complex data types including objects, arrays, and primitive values. It also provides custom serialization options for advanced use cases like Date objects, includes error handling capabilities, and automatically syncs changes across browser tabs using the storage event. This hook uses our own custom hook useEventListener to listen for storage changes across tabs.

A simple example demonstrating primitive value storage with automatic persistence:

Session Interaction Counter
0
const [value, setValue, removeValue] = useSessionStorage(key, initialValue)
Tracks interactions and nickname for this session only - close tab to clear

This example shows how to store and manage basic data types like numbers and strings. The counter persists across page refreshes, and the name input maintains its value even when navigating away and back.

Installation

pnpm dlx shadcn@latest add https://shaddy-docs.vercel.app/r/use-session-storage

Store Complex Objects with Automatic Serialization

Complex object storage with nested properties and automatic serialization:

Session UI Preferences

Session Saved
Current UI Settings:
{
  "showBanner": true,
  "showTooltips": true,
  "highContrast": false
}
useSessionStorage('session-ui-settings', defaultObject)
UI preferences persist only for this session - close tab to reset

This example demonstrates storing complex objects with multiple properties. The settings object is automatically serialized to JSON and stored in sessionStorage, with all changes immediately persisted and synchronized across tabs.

Form Draft Auto-Save

Automatic form data persistence to prevent data loss during editing:

Session Note Draft

Auto-saves note draft in session - close tab to clear!

This example shows how to implement auto-save functionality for forms. As users type, their input is automatically saved to sessionStorage, preventing data loss if they accidentally close the tab or refresh the page.

Advanced Features with Custom Serialization

Custom serialization for complex data types and multiple storage patterns:

Session Analytics

Track Session Events

Total Events: 0
Tracks session events with custom serialization

This advanced example demonstrates custom serialization for Date objects and managing arrays of complex objects like a session analytics tracker. It shows how to handle data types that don't serialize well with JSON by default.

API

useSessionStorage<T>(key, initialValue?, options?): [T, Dispatch<SetStateAction<T>>, () => void]

Parameters

ParameterTypeDescription
keystringThe sessionStorage key to store the value under
initialValueT | (() => T) | undefinedThe initial value or a function to compute it. Defaults to undefined
optionsUseSessionStorageOptions<T> | undefinedOptional configuration for serialization, initialization, and error handling

Options

The options parameter provides advanced configuration:

PropertyTypeDefaultDescription
serializer(value: T) => string | undefinedJSON.stringifyCustom function to serialize the value before storing in sessionStorage
deserializer(value: string) => T | undefinedJSON.parseCustom function to deserialize the value when reading from sessionStorage
initializeWithValueboolean | undefinedtrueWhether to initialize with value from sessionStorage on mount
onError(error: Error, key: string) => void | undefinedConsole warningError handler called when sessionStorage operations fail

Returns

Returns a tuple with three elements:

IndexTypeDescription
0TThe current value from sessionStorage or the initial value
1Dispatch<SetStateAction<T>>A setter function that accepts a value or updater function (same API as useState)
2() => voidA function to remove the item from sessionStorage and reset to initial value

Types

type UseSessionStorageOptions<T> = {
  serializer?: (value: T) => string
  deserializer?: (value: string) => T
  initializeWithValue?: boolean
  onError?: (error: Error, key: string) => void
}