Skip to content
usefy

useSessionStorage

Storage

A lightweight React hook for persisting state in sessionStorage with automatic same-tab synchronization

Install

$ npm install @usefy/use-session-storage

Quick 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

ParameterTypeDescription
keystringThe sessionStorage key
initialValueT | () => TInitial value or lazy initializer function
optionsUseSessionStorageOptions<T>Configuration options

Options

OptionTypeDefaultDescription
serializer(value: T) => stringJSON.stringifyCustom serializer function
deserializer(value: string) => TJSON.parseCustom deserializer function
onError(error: Error) => voidCallback for error handling

Returns [T, SetValue<T>, RemoveValue]

IndexTypeDescription
[0]TCurrent stored value
[1]Dispatch<SetStateAction<T>>Function to update value (same as useState)
[2]() => voidFunction 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.

More in storage