Theme Toggle Implementation with CSS Variables
You'll learn how to wire up a working light/dark mode toggle by combining React's useState, CSS variables, and root-level class switching for instant theme changes.
The Complete Pattern
You've already seen CSS variables and how to set them from components. Now we'll assemble a full toggle system. The strategy: store CSS variables for both themes in separate CSS classes, use React state to track the active theme, and apply that class to the document root.
Setting Up the CSS
Define your theme variables under class names:
:root.light {
--bg-color: #ffffff;
--text-color: #000000;
}
:root.dark {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}
Building the Toggle Component
Use useState to track the current theme, then apply it to document.documentElement.className:
import { useState, useEffect } from 'react';
function ThemeToggle() {
const [theme, setTheme] = useState('light');
useEffect(() => {
document.documentElement.className = theme;
}, [theme]);
const toggleTheme = () => {
setTheme(prev => prev === 'light' ? 'dark' : 'light');
};
return (
<button onClick={toggleTheme}>
Switch to {theme === 'light' ? 'dark' : 'light'} mode
</button>
);
}
How It Works
When theme changes, the effect updates the root element's class. CSS immediately applies the matching variable set. Your entire app styled with var(--bg-color) and var(--text-color) updates instantly—no prop drilling, no re-renders needed.
Key Takeaway: Theme toggling with CSS variables is a three-part dance: define theme classes with variables, manage active theme in React state, and sync that state to the root element's class via useEffect.