Persistent State in React
Sync React state with localStorage using a custom hook that reads on mount and writes on every state change.
Sync React state with localStorage using a custom hook that reads on mount and writes on every state change.
import { useState, useEffect } from "react";
function useLocalStorage(key, defaultValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : defaultValue;
} catch {
return defaultValue;
}
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
// Usage
const [theme, setTheme] = useLocalStorage("theme", "light");
Initialize useState with a function (lazy initializer) when reading from localStorage to avoid reading on every render.
More in JavaScript