Part 07 / Topic 5 of 6
useLocalStorage: a hook that uses useEffect correctly, internally
A custom hook can use any hook it needs - the component calling it never has to know, or write the effect itself. examples/05_use_local_storage.jsx's useLocalStorage reads once (via useState's lazy initializer, a function that only ever runs on the first render) and writes on every change (via useEffect):
// examples/05_use_local_storage.jsx
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = window.localStorage.getItem(key);
return stored !== null ? JSON.parse(stored) : initialValue;
} catch {
return initialValue;
}
});
useEffect(() => {
window.localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue];
}
ThemePreference, using it, really starts at "light" with nothing in storage, really writes "dark" to localStorage the moment it is toggled, and really reads "dark" back on a fresh mount simulating a page reload (examples/05_use_local_storage.test.jsx, unmounting and remounting the same component). The component itself never calls localStorage.getItem/setItem directly - it just calls useLocalStorage, the same way useWindowWidth's callers never touch addEventListener directly.
Done here? The practice set for Part 7 — including the solutions — is on the part page.