Persisting Theme Choice in localStorage
You'll learn how to remember the user's theme preference across browser sessions, eliminate the initial load "flash" of wrong theme, and keep the theme in sync across multiple tabs.
The Problem
Without persistence, users pick a theme — then lose it the moment they refresh or close the tab. Worse, the default theme might flash briefly before JavaScript runs and applies the saved choice. This creates a jarring experience.
The Solution: localStorage + Early Script
Save on change:
When the user toggles the theme, write their choice to localStorage.setItem('theme', 'dark'). Your component reads this on mount with useState(() => localStorage.getItem('theme') || 'light').
Eliminate flash:
The trick is running a tiny blocking script in <head> (before React loads) that reads localStorage and immediately applies the theme attribute:
<script>
(function() {
const saved = localStorage.getItem('theme');
if (saved) document.documentElement.setAttribute('data-theme', saved);
})();
</script>
This ensures the correct theme is active before the page renders.
Sync across tabs:
Listen to the storage event, which fires when localStorage changes in another tab:
useEffect(() => {
const handleStorage = (e) => {
if (e.key === 'theme') setTheme(e.newValue);
};
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, []);
Now all tabs stay in sync automatically.
Analogy
Think of localStorage as a sticky note on the user's desk. The inline script checks the note before opening the app (no flash). The storage event is like a notification system — when one tab updates the note, others get notified instantly.
Key Takeaway:
Save theme choices in localStorage, use an inline script in <head> to prevent flash-of-wrong-theme, and sync across tabs with the storage event for a seamless, persistent theming experience.