Setting CSS Variables from React Components
What you'll learn: How to dynamically update CSS custom properties from React to create powerful, performant theming systems.
The Core Idea
CSS variables (custom properties) can be set and updated from JavaScript, making them a bridge between React's dynamic component state and CSS's styling power. Unlike fully re-rendering styled components, updating CSS variables is incredibly fast—the browser handles the cascading updates natively.
Think of CSS variables as dials on a control panel. Instead of rebuilding the entire panel (re-rendering styled components) every time you want to change a setting, you just turn the dial (update the variable value). The panel already knows how to respond to each dial position.
Three Key Techniques
1. Inline Styles with style Prop
The most direct approach—set variables right on an element:
function ThemedBox({ primaryColor }) {
return (
<div
style={{ '--primary-color': primaryColor }}
className="themed-box"
>
Content
</div>
);
}
CSS variables use the -- prefix and can be referenced in your stylesheet. The style object treats them as regular properties.
2. Root-Level Variables for Global Theming
Apply variables at the document root to affect the entire app:
function ThemeProvider({ theme, children }) {
useEffect(() => {
document.documentElement.style.setProperty('--bg-color', theme.background);
document.documentElement.style.setProperty('--text-color', theme.text);
}, [theme]);
return <>{children}</>;
}
3. ClassName Switching
Toggle between predefined variable sets:
<div className={isDark ? 'theme-dark' : 'theme-light'}>
{/* CSS classes define different --variable values */}
</div>
Key Takeaway: CSS variables bridge React's dynamic state with CSS's performance—use inline styles for component-scoped variables, root-level setting for global themes, and className switching for discrete theme variants.