Join our Discord Community

React useSessionStorage Hook

React useSessionStorage hook for session storage management. Persist temporary state across page reloads with automatic serialization using TypeScript for Next.js.

Need help with session persistence?

Join our Discord community for help from other developers.


Ever tried to manage sessionStorage in React and ended up with JSON.stringify chaos, serialization error nightmares, or broken state synchronization? You know the drill—manually calling sessionStorage.setItem(), forgetting to handle JSON parsing errors, dealing with cross-component state sync, missing cleanup on component unmount. This free open source React useSessionStorage custom hook handles all that session storage complexity so you can focus on building stateful features instead of debugging storage edge cases in your React applications.

useSessionStorage showcase

Smart session storage with automatic serialization and state synchronization:

Loading component...

This free open source React hook simplifies temporary state persistence with TypeScript support for modern JavaScript applications. Whether you're building form persistence, shopping carts, or user preferences in your Next.js projects, this React hook keeps your session data reliable and reactive.

Installation

npx shadcn@latest add https://www.shadcn.io/registry/use-session-storage.json
npx shadcn@latest add https://www.shadcn.io/registry/use-session-storage.json
pnpm dlx shadcn@latest add https://www.shadcn.io/registry/use-session-storage.json
bunx shadcn@latest add https://www.shadcn.io/registry/use-session-storage.json

Why most sessionStorage implementations suck

Look, you could keep manually managing sessionStorage.setItem() and JSON parsing. But then you hit the session storage complexity—serialization errors breaking your app, stale data when other components update storage, SSR hydration mismatches, performance issues from repeated parsing in React applications.

Most developers manually call sessionStorage.setItem() with JSON.stringify() without proper error handling, causing app crashes when serialization fails in TypeScript components. Or they forget about cross-component synchronization and wonder why updating storage in one component doesn't reflect in others. Some skip SSR considerations entirely and get hydration mismatches when session data differs between server and client in Next.js projects.

This React hook uses optimized storage management under the hood, with automatic serialization and cross-component synchronization in JavaScript applications. The browser handles all the storage events, plus you get comprehensive error handling and type safety in one call.

Plus it handles all the edge cases—SSR compatibility with proper hydration, automatic JSON serialization with fallbacks, cross-component state sync, proper cleanup on unmount in React development. No more broken form data or inconsistent state management.

This free open source React hook manages session state while you focus on building features. Whether you're creating React applications, Next.js dashboards, or TypeScript components, reliable session storage keeps your JavaScript development smooth.

Features

  • Session persistence maintaining state across page reloads within the same browser tab in React applications
  • Type-safe storage with full TypeScript support for complex objects and primitives in TypeScript components
  • Custom serialization allowing custom serializer and deserializer functions for complex types in Next.js projects
  • Cross-component sync updating state when sessionStorage changes in other components in JavaScript development
  • SSR compatibility with proper server-side rendering support and initialization options for React frameworks
  • Error handling with graceful fallbacks and console warnings for debugging in modern applications
  • Free open source designed for modern React development workflows

When you'll actually use this

Real talk—this isn't for every temporary data need in React applications. React useState handles most component state perfectly. But when you need state persistence across page refreshes within a browser session, this React hook delivers in Next.js projects.

Perfect for:

  • Form draft saving - Preserve form inputs during page reloads and navigation built with TypeScript
  • Shopping cart sessions - Maintain cart items during the browsing session using React patterns
  • Multi-step wizards - Save progress through complex form workflows in JavaScript applications
  • User preferences - Store temporary UI settings and theme choices in React components
  • Search filters - Remember applied filters and sorting across page loads in Next.js applications
  • Draft content - Preserve unsaved articles, comments, or message drafts using TypeScript safety

API Reference

useSessionStorage

useSessionStorage<T>(
  key: string,
  initialValue: T | (() => T),
  options?: UseSessionStorageOptions<T>
): [T, Dispatch<SetStateAction<T>>, () => void]
ParameterTypeDescription
keystringStorage key for the sessionStorage item
initialValueT | (() => T)Initial value or function returning initial value
optionsUseSessionStorageOptions<T>Configuration options for serialization and initialization

UseSessionStorageOptions

PropertyTypeDefaultDescription
serializer(value: T) => stringJSON.stringifyCustom function to serialize values before storage
deserializer(value: string) => TJSON.parseCustom function to deserialize values from storage
initializeWithValuebooleantrueWhether to initialize with stored value immediately (set to false for SSR)

Return Value

Returns a tuple with three elements:

IndexTypeDescription
[0]TCurrent stored value with automatic synchronization
[1]Dispatch<SetStateAction<T>>Function to update the stored value (supports functional updates)
[2]() => voidFunction to remove the item from storage and reset to initial value

Common gotchas

SessionStorage is tab-specific: Data stored in one browser tab won't be available in other tabs, even for the same website in React applications. This is different from localStorage which is shared across tabs. The isolation is actually a feature for temporary session data.

Serialization errors are handled gracefully: If JSON.stringify fails during storage or JSON.parse fails during retrieval, the React hook logs the error and uses fallback values in TypeScript components. Complex objects with circular references may need custom serializers.

Cross-component synchronization is automatic: When one component updates a storage key, all other components using the same key will re-render with the new value instantly in Next.js projects. This happens through custom events, not storage events.

SSR requires careful initialization: Use initializeWithValue: false to prevent hydration mismatches in JavaScript applications. The React hook will return your initial value during SSR and update with stored data after hydration.

Storage size limitations: SessionStorage has size limits (usually 5-10MB) in React frameworks. The hook handles quota exceeded errors gracefully but won't prevent them.

Tab closure clears data: All sessionStorage data is permanently lost when the user closes the tab in TypeScript projects. Consider this behavior when designing user flows that depend on session persistence.

Questions you might have