useSessionStorage
StorageA lightweight React hook for persisting state in sessionStorage with automatic same-tab synchronization
Install
$ npm install @usefy/use-session-storageQuick start
useSessionStorage.tsx
import { useSessionStorage } from "@usefy/use-session-storage";
function CheckoutForm() {
const [formData, setFormData, clearForm] = useSessionStorage(
"checkout-form",
{
name: "",
email: "",
address: "",
}
);
return (
<form>
<input
value={formData.name}
onChange={(e) =>
setFormData((prev) => ({ ...prev, name: e.target.value }))
}
placeholder="Name"
/>
<input
value={formData.email}
onChange={(e) =>
setFormData((prev) => ({ ...prev, email: e.target.value }))
}
placeholder="Email"
/>
<button type="button" onClick={clearForm}>
Clear Form
</button>
</form>
);
}API reference
useSessionStorage<T>(key, initialValue, options?)
A hook that persists state in sessionStorage for the duration of the browser session.
Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | The sessionStorage key |
initialValue | T | () => T | Initial value or lazy initializer function |
options | UseSessionStorageOptions<T> | Configuration options |
Options
| Option | Type | Default | Description |
|---|---|---|---|
serializer | (value: T) => string | JSON.stringify | Custom serializer function |
deserializer | (value: string) => T | JSON.parse | Custom deserializer function |
onError | (error: Error) => void | — | Callback for error handling |
Returns [T, SetValue<T>, RemoveValue]
| Index | Type | Description |
|---|---|---|
[0] | T | Current stored value |
[1] | Dispatch<SetStateAction<T>> | Function to update value (same as useState) |
[2] | () => void | Function to remove value and reset to initial |
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.