Skip to main content

useSessionStorage

useSessionStorage is a custom hook for syncing state with sessionStorage.

Usage

import { useSessionStorage } from "hookify-react";

export default function UseSessionStorage() {
const [name, setName] = useSessionStorage<string>("name", "default name");

return (
<div>
<p>Your name is {name}</p>
<input value={name} onChange={(e) => setName(e.target.value)} />
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
keystringThe storage key used to retrieve and store data.
defaultValueT | (() => T)The default value, or a lazy initializer function returning it, used when no value is found in sessionStorage.

Return Value

A tuple [value, setValue].

PropertyTypeDescription
[0]TThe current stored value.
[1]Dispatch<SetStateAction<T>>Function to update the stored value (accepts a value or an updater function).

Behavior

  • Wraps useStorage internally with the "session" storage type.
  • Persists values to sessionStorage and reads the initial value from it, falling back to defaultValue.
  • Removes the key from sessionStorage when the value is undefined.
  • Uses JSON parse/stringify with error handling, and guards against sessionStorage being unavailable (private mode, sandboxed iframes).
  • Does not sync across tabs/windows (cross-tab storage events apply to localStorage only).

SSR Safety

useSessionStorage is SSR-safe. On the server it falls back to defaultValue and performs no storage access, making it safe for server-rendered apps.