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
| Parameter | Type | Default | Description |
|---|---|---|---|
key | string | — | The storage key used to retrieve and store data. |
defaultValue | T | (() => 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].
| Property | Type | Description |
|---|---|---|
[0] | T | The current stored value. |
[1] | Dispatch<SetStateAction<T>> | Function to update the stored value (accepts a value or an updater function). |
Behavior
- Wraps
useStorageinternally with the"session"storage type. - Persists values to
sessionStorageand reads the initial value from it, falling back todefaultValue. - Removes the key from
sessionStoragewhen the value isundefined. - Uses JSON parse/stringify with error handling, and guards against
sessionStoragebeing unavailable (private mode, sandboxed iframes). - Does not sync across tabs/windows (cross-tab
storageevents apply tolocalStorageonly).
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.