useSessionstorageState
About
A hook that provides state management synchronized with sessionStorage. It automatically persists state changes to sessionStorage and provides real-time synchronization across browser windows and tabs. The hook handles JSON serialization/deserialization automatically and provides a clean API similar to React's useState.
Examples
Basic example
Complex object storage
Cross-window synchronization with remove functionality
Arguments
Argument | Type | Description | Default |
---|---|---|---|
key | string | The sessionStorage key to use for persistence | - |
initialState | S | (() => S) | Initial state value or function that returns initial state | - |
Returns
Returns an array with three elements:
Return value | Type | Description |
---|---|---|
value | S | Current state value, synchronized with sessionStorage |
setValue | Dispatch<SetStateAction<S>> | Function to update the state (similar to useState) |
remove | () => void | Function to remove the item from sessionStorage |
Features
Automatic Persistence
- State changes are automatically saved to sessionStorage
- Values are JSON serialized/deserialized automatically
- Handles complex objects, arrays, and primitive values
Cross-Window Synchronization
- Changes in one browser tab/window automatically sync to other tabs/windows
- Uses native
storage
events for cross-document communication - Real-time updates without page refresh
Within-Document Synchronization
- Multiple instances of the same hook with the same key stay synchronized
- Uses custom events for efficient within-document communication
- Prevents infinite update loops
Error Handling
- Gracefully handles JSON parsing errors
- Safe fallback when sessionStorage is unavailable (SSR)
- Console warnings for debugging in non-browser environments
Memory Management
- Automatically cleans up event listeners on unmount
- Optimized re-renders using useCallback and useRef
- No memory leaks from event listeners
Notes
- The hook is SSR-safe and handles cases where
window
orsessionStorage
are undefined - Values are stored as JSON strings, so only JSON-serializable values are supported
- sessionStorage data persists until the browser tab is closed (unlike localStorage which persists indefinitely)
- Cross-window synchronization only works within the same domain and browser session