shadimage
Hookagain
hookuse-local-storagesource: ok · refreshed

Use Local Storage

npx shadcn add "https://hookagain.vercel.app/r/use-local-storage.json"
free

No selection tags yet — empty means no evidence, not lack of support.

Files1 · source cached 10/2/2026, 1:57:53 AM

hooks/use-local-storage.ts
import * as React from "react";

export function useLocalStorage<T>(
	key: string,
	defaultValue: T,
): [T, (value: T) => void] {
	const [value, setValue] = React.useState(defaultValue);

	React.useEffect(() => {
		const item = localStorage.getItem(key);

		if (!item) {
			localStorage.setItem(key, JSON.stringify(defaultValue));
		}

		setValue(item ? JSON.parse(item) : defaultValue);

		function handler(e: StorageEvent) {
			if (e.key !== key) return;

			const lsi = localStorage.getItem(key);

			setValue(JSON.parse(lsi ?? ""));
		}

		window.addEventListener("storage", handler);

		return () => {
			window.removeEventListener("storage", handler);
		};
	}, []);

	const setValueWrap = (value: T) => {
		try {
			setValue(value);

			localStorage.setItem(key, JSON.stringify(value));
			if (typeof window !== "undefined") {
				window.dispatchEvent(new StorageEvent("storage", { key }));
			}
		} catch (e) {
			console.error(e);
		}
	};

	return [value, setValueWrap];
}

More from Hookagain

Browse all components in this library →