useLocalStorage
function useLocalStorage<T>(
key: string,
initialValue: T,
): readonly [value: T, set: SetStoredValue<T>, remove: () => void];
type SetStoredValue<T> = (value: T | ((previous: T) => T)) => void;
Works like useState, but keeps the value in localStorage as JSON so it survives reloads.
valueisinitialValuewhile nothing is stored, when the stored text isn't valid JSON, during server rendering and on the first render while hydrating.setaccepts a value or an updater; the updater always receives the latest stored value.removedeletes the key, sovaluereturns toinitialValue.- Every hook using the same key updates together, in this page and in other tabs.
valuekeeps its identity until the stored value changes, andset/removekeep theirs whilekeyis unchanged, so all three are safe in effect dependencies.- If storage is blocked or full, reads fall back to
initialValueand writes are kept in memory for this page instead of throwing.
Values must survive JSON.stringify: no functions, Dates come back as strings, and
undefined is not stored.
Live demo
Hello, stranger!
Reload the page: your name stays.
Example
import { useLocalStorage } from "react-honey-hooks";
function ThemeToggle() {
const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");
return (
<button
onClick={() => {
setTheme((t) => (t === "light" ? "dark" : "light"));
}}
>
Switch to {theme === "light" ? "dark" : "light"} mode
</button>
);
}