Is it time to ditch your React ThemeProvider?

Dominic Tobias
2 min readMar 8, 2020

JS-in-CSS is now common practice, and your framework of choice probably provides a means to theme with JS Objects and a Provider. I’m going to put the case forward that you’re better off choosing CSS Variables for performance, and how you can easily use them with any framework and still allow the consumer of your components to use JS Objects for convenience.

Changing CSS Variables (e.g. changing themes) is significantly more performant, it doesn’t require React to re-render your entire app (or re-render almost anything in fact) and the changes will be instant. This is why frameworks like Emotion have experiments to use CSS Variables (psst, did you know Emotion wraps every.single.component in your app in a Consumer and styled ones in a HOC, all for theming!?).

On top of this you pay a performance penalty for adding dynamism via props to your CSS. That’s why frameworks like styled-jsx give advise to split static and dynamic sections of your CSS out, or lit-element advising that “For optimal performance, define scoped styles in a static styles property.”.

I’m also of the camp that littering your CSS with logic often per property makes it less readable and maintainable. And you don’t need to pollute your JavaScript with useTheme hooks or Consumers, the variables just… work.

It turns our it’s remarkably easy to use CSS Vars with any solution. Given a JS Object convert the keys to start with -- (I’ve added a namespace for good measure), and simply pass the object to the style attribute:

Here’s a demo using Emotion:

--

--

Dominic Tobias

Interested in programming and fintech: JS, WASM, Rust, Go, blockchain, L1/2, DApps, trading