Write a custom hook for local storage
Wrap useState and localStorage in a reusable useLocalStorage hook, with a lazy initializer and a safe fallback when storage is unavailable.
Several components need a value that survives a refresh. A custom hook puts the read and write in one place and behaves like useState.
import { useEffect, useState } from 'react';
export function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const stored = localStorage.getItem(key);
return stored === null ? initialValue : JSON.parse(stored);
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// storage is full or blocked, keep the in-memory value
}
}, [key, value]);
return [value, setValue];
}import { useLocalStorage } from './useLocalStorage.js';
export function Theme() {
const [theme, setTheme] = useLocalStorage('theme', 'light');
return <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>{theme}</button>;
}light (first visit)
dark (after a click, and still dark after a reload)Passing a function to useState runs it only on the first render, so storage is not read again every time. Both calls sit in try because Safari private mode and some embedded browsers throw on access.
On a server-rendered page, localStorage does not exist during render, so read it in an effect or guard with typeof window. Otherwise the first client render differs from the server HTML.