Skip to content

useSessionStorage

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

useSessionStorage

Synchronize a React state variable directly with the browser's sessionStorage. Data persists perfectly across hot-reloads and page refreshes, but is completely cleared when the browser tab or window is closed. It automatically handles JSON.parse and JSON.stringify under the hood.

Usage Examples

Basic

A simple string value synced to sessionStorage.

import { useSessionStorage } from "react-hook-lab";

function DraftForm() {
  const [draft, setDraft] = useSessionStorage("draft_text", "");

  return (
    <div>
      <textarea 
        value={draft} 
        onChange={(e) => setDraft(e.target.value)} 
        placeholder="Type here... it survives reloads!" 
      />
      <button onClick={() => setDraft("")}>Clear</button>
    </div>
  );
}

Common

Syncing complex objects or arrays. The hook automatically handles the JSON serialization and parsing for you safely.

import { useSessionStorage } from "react-hook-lab";

interface UserPrefs {
  volume: number;
  showSubtitles: boolean;
}

function VideoPlayer() {
  const [prefs, setPrefs] = useSessionStorage<UserPrefs>("video_prefs", {
    volume: 50,
    showSubtitles: false
  });

  return (
    <div>
      <button onClick={() => setPrefs({ ...prefs, showSubtitles: !prefs.showSubtitles })}>
        Subtitles: {prefs.showSubtitles ? "ON" : "OFF"}
      </button>
    </div>
  );
}

Advanced

Using standard useState functional updates to derive the next state from the previous state.

import { useSessionStorage } from "react-hook-lab";

function Counter() {
  const [count, setCount] = useSessionStorage("session_counter", 0);

  const increment = () => {
    // You can pass a callback just like standard useState!
    setCount((prev) => prev + 1);
  };

  return <button onClick={increment}>Count: {count}</button>;
}

API Reference

Parameters

  • key
    • Type: string
    • Description: The unique string key used to store the data inside window.sessionStorage.
  • initialValue
    • Type: T
    • Description: The fallback value returned if the key does not exist in storage (or during Server Side Rendering).

Return Array

Returns a standard React state tuple:

  • value (T): The current state, read from sessionStorage (or the initialValue).
  • setStoredValue ((newValue: T | ((prev: T) => T)) => void): A setter function that updates both the React state and the browser's sessionStorage simultaneously.

Core Working

On the initial render, useSessionStorage attempts to read the specified key from the browser. If it exists, it safely attempts a JSON.parse(). If parsing fails or the key doesn't exist, it falls back to the initialValue.

When setStoredValue is invoked, it updates the internal React useState (triggering a re-render) while synchronously writing the JSON.stringify() version of your payload back into the window.sessionStorage. The hook is fully SSR-safe by guarding window checks, ensuring it gracefully falls back to initialValue when executed on the server.

Clone this wiki locally