useSessionStorage
Typed sessionStorage state.
Import
TypeScript
import { useSessionStorage } from '@/hooks';API
Signature
useSessionStorage<T>(key, defaultValue, options?)
When to use
Use useSessionStorage instead of re-implementing the same pattern in multiple components.
SSR / Next.js
Uses defaultValue on the server; rehydrates after mount.
Live playground
Edit the example and see it run against the real @/hooks package in this app.
Live playgroundEdit · run with real
@/hooks · useSessionStorageEditor
function Wizard() { const [step, setStep] = useSessionStorage('wizard-step', 0); return <button onClick={() => setStep((s) => s + 1)}>Step {step}</button>; }
Preview
Implementation source
Full library source for useSessionStorage — copy into your project when you are not installing a package yet.
hooks/storage/useSessionStorage.ts
import {
useStorage,
type UseStorageOptions,
type UseStorageReturn,
} from './useStorage';
/** `sessionStorage`-backed state. */
export function useSessionStorage<T>(
key: string,
defaultValue: T,
options?: UseStorageOptions<T>,
): UseStorageReturn<T> {
return useStorage('session', key, defaultValue, {
sync: false,
...options,
});
}
Copy-paste example
useSessionStorage.example.tsx
'use client';
import { useSessionStorage } from '@/hooks';
export function Wizard() {
const [step, setStep] = useSessionStorage('wizard-step', 0);
return <button onClick={() => setStep((s) => s + 1)}>Step {step}</button>;
}Production checklist
- Called only from Client Components or other custom hooks
- Type parameters filled in (e.g.
useFetch<User[]>) - Tip: Only store JSON-serializable values. Theme keys should match across tabs.
- Source of truth: open
hooks/storage/useSessionStorage.tsfor implementation details