Why I Write CSS in JavaScript

Avatar of Chris Coyier
Chris Coyier on

Take the pain out of building site search with the Algolia hosted API. Start free now!

I’m never going to tell you that writing your CSS in CSS (or some syntactic preprocessor) is a bad idea. I think you can be perfectly productive and performant without any tooling at all. But, I also think writing CSS in JavaScript is a good idea for component-based styles in codebases that build all their components with JavaScript anyway.

In this article, Max Stoiber focuses on why to write CSS in JavaScript rather than how to do it. There is one reason that resonates strongly with me, and that’s confidence. This is what styling confidence means to me.

  • Anyone on a team can work on styling a component without any fear of unintended side effects.
  • There is no pressure to come up with perfect names that will work now and forever.
  • There is no worry about the styles needing to be extremely re-usable or that they play friendly with anything else. These styles will only be used when needed and not any other time.
  • There is an obvious standard to where styles are placed in the codebase.
  • CSS in JavaScript isn’t the only answer to those things, but as Max connects to other posts on the topic, it can lead to situations where good choices happen naturally.

    There are some reasons why I don’t buy into it. Performance is one of them, like choosing CSS-in-JS is some automatic performance win. Part of the problem (and I’m guilty of doing it right here) is that CSS-in-JS is a wide scope of solutions. I’ve generally found there is no big performance wins in CSS-in-JS (more likely the opposite), but that’s irrelevant if we’re talking about something like CSS modules with the styles extracted and linked up like any other CSS.

    Direct Link →