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]);

Explanation

In SSR apps localStorage doesn't exist on the server, so read it after mount (or use useSyncExternalStore) to avoid hydration mismatches.

Further reading

Problem with a question

State Management · Junior · question 73

Test yourself

Take the State Management · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz