DEV Community

Discussion on: CSS Modules vs CSS-in-JS. Who wins?

Collapse
 
greggcbs profile image
GreggHume • Edited

I ran into issues with css modules that styled components seemed to solve. But i ran into issues with styled components that I wouldn't have had with plain scss.

So some things to think about:
Styled components is a lot more overhead because all the styled components need to be complied into stylesheets and mounted to the head by javascript which is a blocking language.

On SSR styled components get compiled into a ServerStyleSheet that then hydrate the react dom tree in the browser via the context api. So even then the mounting of styles only happens in the browser but the parsing of styles happens on the server - that is still a performance penalty and will slow down the page load.

In some cases I had no issues with styled components but as my site grew and in complex cases I couldn't help but feel like it was slower, or didn't load as smoothly... and in a world where every second matters, this was a problem for me.

Here is an article doing benchmarks on CSS vs CSS in JS:
pustelto.com/blog/css-vs-css-in-js...

I use nextjs, it is a pity they do not support component level css and we are forced to use css modules or styled components... where as with Nuxt component level scss is part of the package and you have the option on how you want the sites css to bundled - all in one file, split into their own files and some other nifty options. I hope nextjs sharped up on this.

Collapse
 
kachidk profile image
Nwanguma Victor • Edited

A big tip that might help.
Why not use SCSS and unique classNames: For example create a unique container className (name of the component) and nest all the other classNames under that unique container className.

.home-page-guest {
  .nav {}
  .main {}
  .footer {}
}
Enter fullscreen mode Exit fullscreen mode
<div className="home-page-guest">
  <div className="nav" />
  <div className="main" />
  <div className="footer" />
</div>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vossyjc profile image
Cindy Vos

I bet you did Greg