Rooks
HooksState Management

useSessionstorageState

Persists React state in sessionStorage and synchronizes matching hook instances.

About

useSessionstorageState reads and writes JSON data in sessionStorage. It persists reloads for the lifetime of a tab and synchronizes mounted hook instances that use the same key and storage area.

Example

import { useSessionstorageState } from "rooks";

export default function SessionDraft() {
  const [draft, setDraft, remove] = useSessionstorageState("message-draft", "");

  return (
    <section>
      <label htmlFor="draft">Draft message</label>
      <textarea
        id="draft"
        value={draft}
        onChange={(event) => setDraft(event.currentTarget.value)}
      />
      <button type="button" onClick={() => setDraft("")}>
        Clear editor
      </button>
      <button type="button" onClick={remove}>
        Remove stored draft
      </button>
    </section>
  );
}

Parameters

  • key: string — required sessionStorage key.
  • initialState?: S | (() => S) — direct or lazily computed fallback when the key is absent or storage cannot be read. It defaults to undefined.

Return value

The hook returns [value, setValue, remove]:

  • value: S — the current in-memory value.
  • setValue: Dispatch<SetStateAction<S>> — resolves a value or functional updater, persists it, and broadcasts it to same-key hook instances in the document.
  • remove(): void — removes the storage item. It does not change or broadcast the current in-memory value.

Behavior and lifecycle

Values are serialized with JSON.stringify and parsed with JSON.parse. Changing key loads the new key before it is persisted. Same-document custom events and browser storage events update matching instances without echo-writing the synchronized value. Event listeners follow the key and are removed on unmount. Rapid functional setters resolve against the most recently stored value.

Setting the value to undefined removes the storage item while leaving the in-memory value undefined. Storage, parsing, and quota failures are logged; state continues in memory when possible.

sessionStorage is partitioned by origin and top-level browsing context. Separate tabs generally do not share live session state; same-origin frames that share the storage area can receive storage events.

Compatibility and accessibility

On the server, the initializer supplies the value because storage is unavailable. A stored browser value can therefore produce different hydration markup; use a client boundary or defer storage-dependent output when needed. Privacy settings can deny access, and persisted values must be JSON-serializable. See SSR and browser APIs.

On this page