A theme switcher: CSS variables, system preference and a saved choice
The first line depends on your system setting: the checker's browser is in light mode. Choose dark and the whole page changes through one attribute. Choose system and switch your OS to dark mode: the page follows live. In the preview, localStorage is in memory and resets on each Run.
Themes are sets of CSS variables switched by one attribute on <html>; the app follows the system setting (prefers-color-scheme) unless the user picks light or dark, remembers that choice, applies it before the first paint so the page never flashes the wrong colours, respects reduced motion, and offers keyboard shortcuts and a command palette for power users.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a useTheme() hook that returns { choice, theme, setChoice } and can be used from any component (hint: context or an external store).
Add Escape and a click outside to close the command palette, and make Ctrl+K toggle it.
Explain it without notes
How would you implement light, dark and system themes in a React app?
What causes a flash of the wrong theme and how do you prevent it?
How do you read and react to prefers-color-scheme and prefers-reduced-motion in React?
What are the rules for good keyboard shortcuts?
Preview
Console
Nothing logged yet.Expected console output
choice system -> theme light, reduced motion false
choice dark -> theme dark, reduced motion false
saved: dark, <html data-theme=dark>