Skip to main content

Function: usePersistedState()

usePersistedState<T>(key, initialValue, options?): [T, (value) => void]

Defined in: use-persisted-state.ts:122

A custom React hook for managing state that persists to localStorage, or to another storage such as sessionStorage.

This hook allows you to maintain a state value that is automatically saved to and loaded from storage. It keeps every instance that uses the same key and storage in sync, both in other tabs and in the current tab, and falls back to initialValue when the key is removed. When no storage is available (during server rendering, or when the browser blocks localStorage), the value is kept in memory only.

When key changes, the hook reads the value stored under the new key (or uses initialValue) instead of carrying the previous value across. The setter keeps a stable identity.

Type Parameters​

T​

T

The type of the state value.

Parameters​

key​

string

The unique key used to store the value.

initialValue​

T

The initial value for the state if no value is stored yet.

options?​

UsePersistedStateOptions

Optional storage to use instead of localStorage.

Returns​

[T, (value) => void]

An array containing the current state and a function to update it.

Examples​

const [theme, setTheme] = usePersistedState<"light" | "dark">("theme", "light");

return (
<div style={{ background: theme === "dark" ? "#333" : "#fff", color: theme === "dark" ? "#fff" : "#000" }}>
<p>Current Theme: {theme}</p>
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
Toggle Theme
</button>
</div>
);
const [counter, setCounter] = usePersistedState<number>("counter", 0);

return (
<div>
<p>Counter: {counter}</p>
<button onClick={() => setCounter((prev) => prev + 1)}>Increment</button>
</div>
);
// Kept only for this tab: survives reloads, cleared when the tab closes.
const [draft, setDraft] = usePersistedState("comment-draft", "", {
storage: sessionStorage,
});

return <textarea value={draft} onChange={(e) => setDraft(e.target.value)} />;

For a live, editable example, see the usePersistedState docs page.