All hooks / Storage and URL

useSessionStorage

370 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

State that persists in sessionStorage as JSON for the life of the tab, stays in sync across components, and is safe to server-render.

Renders serverValue on the server and during hydration, then switches to the stored value with no hydration mismatch. Missing or unparseable stored values also read as serverValue. Setting undefined removes the key.

Values go through JSON: a Date comes back as a string, and Map, Set, Infinity, and undefined inside objects don't survive. Store plain data. Writes made directly with sessionStorage in the same tab aren't seen; go through the setter.

Import

import { useSessionStorage } from '@vincent.ri/react-tils'
// or only this hook
import { useSessionStorage } from '@vincent.ri/react-tils/useSessionStorage'

Usage

const [step, setStep] = useSessionStorage('checkout-step', 1)
setStep((s) => s + 1)

const [dismissed, setDismissed] = useSessionStorage('promo-dismissed', false)

Live demo

Reload: both stay. Open a second tab: local syncs, session does not.

local 0
session 0

When to use it

State should survive a reload but not outlive the tab, and each tab keeps its own copy (multi-step form progress, scroll restore, a dismissed banner for this visit).

When not to

The state should be shared between tabs or survive closing the tab; use useLocalStorage. Same limits as localStorage: no sensitive data (any script on the page can read it), no large data.

API

function useSessionStorage<T>(key: string, serverValue: T): [T, SetValue<T>]
ParameterDescription
keyThe sessionStorage key.
serverValueValue on the server, during hydration, and when nothing valid is stored. Pass a primitive or a constant, so the setter stays stable.

Returns [value, setValue], like useState. setValue accepts a value or an updater. If storage is full or blocked, the value still updates for this page session but isn't saved.

Browser support

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
sessionStorageWidely available4+12+2+4+18+3.2+
storage eventWidely available1+15+45+4+18+4+

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).

Coming from another library?

Other libraries call this useSessionStorageState.