Is it time to ditch your React ThemeProvider?

Image for post
Image for post

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 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 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 attribute:

Here’s a demo using Emotion:

I make UIs and such. Using JS mostly but I like to dabble.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store