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:
const [value, setValue, removeValue] = useSessionStorage(key, initialValue)
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
{ "showBanner": true, "showTooltips": true, "highContrast": false }
useSessionStorage('session-ui-settings', defaultObject)
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
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
Parameter | Type | Description |
---|---|---|
key | string | The sessionStorage key to store the value under |
initialValue | T | (() => T) | undefined | The initial value or a function to compute it. Defaults to undefined |
options | UseSessionStorageOptions<T> | undefined | Optional configuration for serialization, initialization, and error handling |
Options
The options
parameter provides advanced configuration:
Property | Type | Default | Description |
---|---|---|---|
serializer | (value: T) => string | undefined | JSON.stringify | Custom function to serialize the value before storing in sessionStorage |
deserializer | (value: string) => T | undefined | JSON.parse | Custom function to deserialize the value when reading from sessionStorage |
initializeWithValue | boolean | undefined | true | Whether to initialize with value from sessionStorage on mount |
onError | (error: Error, key: string) => void | undefined | Console warning | Error handler called when sessionStorage operations fail |
Returns
Returns a tuple with three elements:
Index | Type | Description |
---|---|---|
0 | T | The current value from sessionStorage or the initial value |
1 | Dispatch<SetStateAction<T>> | A setter function that accepts a value or updater function (same API as useState) |
2 | () => void | A 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
}