Skip to content

useLocalStorage

useState persisted to localStorage.

A React hook that mirrors useState but persists the value to localStorage as JSON. Reads lazily on mount and writes on every change.

Installation

pnpm dlx shadcn@latest add @frontal-labs/use-local-storage

Usage

import { useLocalStorage } from "@/hooks/use-local-storage";
 
function ThemeToggle() {
  const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");
 
  return <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>{theme}</button>;
}

Corrupt JSON or unavailable storage falls back to initialValue, and write failures (quota, private mode) fail silently.

API

function useLocalStorage<T>(key: string, initialValue: T): [T, Dispatch<SetStateAction<T>>];

Parameters

Return value

A [value, setValue] tuple matching useState. setValue accepts updater functions and persists the result as JSON.