re: What is Your Opinion about CSS(-in-JS)? VIEW POST


Currently, CSS suffers some long-dated problems:

  • interaction with JavaScript is lacking;
  • we can't always afford the encapsulation of Custom Elements;
  • it's very hard to tree-shake the CSS codebase.

CSS-in-JS aims to solve those problems... and it usually does. If you take something like style-components or Emotion, you can use JavaScript values directly in your styles. Also, they offer emulated encapsulation (i.e. good enough for most) and tree-shakable rules as they're basically JavaScript objects. Perfect, isn't it?

Now the problems:

  • you need JavaScript to style your components: this means you have to wait for JavaScript to download, parse and execute (and of course you're out of luck if JS is disabled altogether);
  • it tends to hide what happens under the hood: what happens when a JS value changes? Does it create another CSS class? Does it put changes inline? Is it performant?
  • fragmentation: there are dozens of CSS-in-JS libraries, each with their syntaxes, quirks and techniques (although just a handful are really widespread); you have reusability as long as you're using the same library;
  • it seems developers are forgetting/not learning what CSS - the engine behind all this anyway - really works: this Twitter poll by Max Stoiber (I'm sure it's the inspiration of this post, together with its following debate) says pretty much about it.

When I have to use CSS-in-JS, I tend to stay as close as "native" CSS as possible. It's usually CSS modules.
For the other problems, it's more about the discipline of keeping your code clean.

But all in all, I'd rather wish the initial problems above solved within CSS than fully adopt a custom solution like CSS-in-JS.

code of conduct - report abuse