TypeScript16 linesUpdated Jul 17, 2026
TypeScript
import { useEffect, useState } from "react";
export function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
try {
const raw = window.localStorage.getItem(key);
return raw ? JSON.parse(raw) : initial;
} catch {
return initial;
}
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}