Skip to main content

useStorage

useStorage is the core hook that synchronizes React state with Web Storage (localStorage or sessionStorage).

Migration note

The third argument changed. It is now the string "local" or "session"not a Storage object as in earlier versions.

// Before
useStorage("key", "default", window.localStorage);

// Now
useStorage("key", "default", "local");

Usage

import { useStorage } from "hookify-react";

export default function Example() {
const [name, setName] = useStorage<string>("name", "default name", "local");

return (
<div>
<p>Your name is {name}</p>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button onClick={() => setName("John Doe")}>Change Name</button>
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
keystringThe storage key used to retrieve and store data.
defaultValueT | (() => T)The default value, or a lazy initializer function returning it, used when no value is found in storage.
type"local" | "session"Which storage area to use: "local" for localStorage or "session" for sessionStorage.

Return Value

A tuple [value, setValue].

PropertyTypeDescription
[0]TThe current stored value.
[1]Dispatch<SetStateAction<T>>Function to update the stored value (accepts a value or an updater function).

Behavior

  • Reads the initial value from the selected storage area, falling back to defaultValue when no value is stored.
  • Parses stored JSON values and stringifies values on write, with error handling around both.
  • Persists to storage whenever the value or key changes.
  • Removes the key from storage when the value is undefined.
  • When type is "local", synchronizes state across browser tabs/windows via the storage event.
  • Guards against storage being unavailable (private/incognito mode, sandboxed iframes) and against read/write failures.

SSR Safety

useStorage is SSR-safe. On the server (where window is unavailable) it falls back to defaultValue and skips all storage access, so it can be used in server-rendered apps without errors or hydration crashes.