Skip to main content

#168: CSS-in-JS

I'm joined by Dustin Schau in this video and he is going to take me on a tour of the world of what has come to be known as CSS-in-JS. That is, doing your styling entirely in JavaScript, rather than in .css files that you <link> up in the head all on your own.

Dustin is a perfect guide for this, as he created a great exploratory tool called CSS in JS Playground and also has a brand new course on the subject.

If you're curious why anyone would be interested in going the CSS-in-JS route at all, here's some reasons we discuss in the video:

  1. Dead code elimination. The only styles that are loaded are the styles for the components in use at any given time. There's no shipping any unused styles. When a component dies, so does its styles.
  2. Scoping. Writing new styles cannot affect anything else in other places on the site, so there's no need to worry about writing a style that has bad or unintended consequences elsewhere due to a selector in the global scope. We get scope protection with naming ideologies like BEM, but it's not tooling-enforced.
  3. Worry-free naming. In some cases, there's no need to pick a class name or ID for what's being styled since the output is contained UI.
  4. Developer ergonomics. It can be nice to have styles in the same file (or otherwise very close to) the component itself. In the same way, some developers feel very comfortable in JSX. Also being able to style things without any scoping worry means developers may feel empowered about styling rather than intimidated by it.
  5. Design system friendly. Design systems are all about components and so is React. These complementary modes of thinking align quite well with one another.
  6. Possibilities of JavaScript in CSS. Doing this with logical operators and passed in values and math and whatnot, having the full power of JavaScript in styles is plenty useful.

And that's not everything, but you can see why it's compelling to some people. It has certainly inspired lots of discussion. Why not when it offers all those benefits? Well, it's a very different development environment that doesn't necessarily click with everyone. It requires bending the web platform to do somewhat unusual things and that comes with warts. Not to mention there is a literal cost to it (size of packages and such) that users pay for, which you'd better hope pays for itself with efficiency.

Dustin went so far as to build out a demo using Sass to style things to compare it with how it can be done with CSS-in-JS, which demonstrates how porting styles looks as well as the possibilities of doing it.

icon-link icon-logo-star icon-search icon-star