Skip to main content

Function: usePersistedState()

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

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

A custom React hook for managing state that persists to localStorage.

This hook allows you to maintain a state value that is automatically saved to and loaded from localStorage. It also synchronizes the state across multiple tabs when the same key is updated elsewhere.

Type Parameters​

T​

T

The type of the state value.

Parameters​

key​

string

The unique key used to store the value in localStorage.

initialValue​

T

The initial value for the state if no value exists in 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>
);

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