State Management · Junior · Question 73 of 75
How can a component remember a setting in localStorage between visits?
const [theme, setTheme] = useState(() => localStorage.getItem("theme") ?? "light");
useEffect(() => localStorage.setItem("theme", theme), [theme]);- ✓Correct answer: Read it in a lazy initializer and write it back in an effect when it changes
- 2Read
localStorageon every render - 3
useStatesaves tolocalStorageautomatically
Explanation
In SSR apps localStorage doesn't exist on the server, so read it after mount (or use useSyncExternalStore) to avoid hydration mismatches.