useSessionStorage
React side-effect hook that manages a single sessionStorage key
useSessionStorage binds a React state to a sessionStorage key. It returns a [value, setValue] tuple that behaves like useState. The value is read from session storage on mount and written back on updates. Setting the value to null removes the key. Like useLocalStorage, it supports custom serializers and listens for cross-tab storage events by default.
When to Use
- Storing temporary state that should persist across page navigations within the same tab but not across browser restarts
- Keeping wizard or multi-step form progress that resets when the user closes the tab
- Caching data that is sensitive or session-specific (e.g., one-time tokens, temporary filters)
Notes
- Session-scoped: Unlike
localStorage, data insessionStorageis cleared when the tab or browser is closed. UseuseLocalStoragefor long-lived persistence. - Cross-tab sync: The hook listens for
storageevents by default. Disable withlistenToStorageChanges: false. - Custom serialization: Provide
serializer.readandserializer.writein the options for non-string data types. - See also
useLocalStoragefor persistent storage anduseCookiefor cookie-based persistence.
Usage
Live Editor
function Demo() { // bind string const [value, setValue] = useSessionStorage("my-key", "key"); return ( <div> <div>Value: {value}</div> <button onClick={() => setValue("bar")}>bar</button> <button onClick={() => setValue("baz")}>baz</button> {/* delete data from storage */} <button onClick={() => setValue(null)}>Remove</button> </div> ); };
Result
API
useSessionStorage
Returns
readonly [T | null, React.Dispatch<React.SetStateAction<T | null>>]: A tuple with the following elements:
- The current value of the sessionStorage.
- A function to update the value of the sessionStorage.
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| key | key | string (Required) | - |
| defaultValue | default value | T | undefined | - |
| options | optional params | UseSessionStorageOptions<T> | undefined | - |
UseSessionStorageOptions
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| serializer | Custom data serialization | UseSessionStorageSerializer<T> | - |
| onError | On error callback | (error: unknown) => void | console.error |
| effectStorageValue | set to storage when nodata in first mount, deprecated | T | (() => T) | - |
| mountStorageValue | set to storage when nodata in first mount | T | (() => T) | - |
| listenToStorageChanges | listen to storage changes | boolean | true |
UseSessionStorageSerializer
| Property | Description | Type | DefaultValue |
|---|---|---|---|
| read | Custom data read | (raw: string) => T (Required) | - |
| write | Custom data write | (value: T) => string (Required) | - |