Sequence NODE_188
MediumBuild a Custom useLocalStorage Hook
React
JavaScript
Technical Specification
Create a custom hook useLocalStorage that syncs state with localStorage.
Input/Output Samples
Input:useLocalStorage("theme", "light")
Output:Persists theme across refresh
Optimal Logic Path
import { useState, useEffect } from "react";
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
if (typeof window === "undefined") return initialValue;
try {
const stored = window.localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
} catch {
// ignore
}
}, [key, value]);
return [value, setValue];
}Architectural Deep-Dive
We lazily initialize state from localStorage and keep it in sync whenever state changes.