paint-brush
I swore never to use CSS in JS, here are 6 reasons why I was wrongby@tal
13,923 reads
13,923 reads

I swore never to use CSS in JS, here are 6 reasons why I was wrong

by Tal BereznitskeyJanuary 11th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

When I first heard of this idea, I was shocked. For decades the best practice was to separate the HTML, CSS and JS concerns. You know, so you can just change the CSS and no need to touch the HTML and JS, right? I guess we all found out at some stage this isn’t true in real projects.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - I swore never to use CSS in JS, here are 6 reasons why I was wrong
Tal Bereznitskey HackerNoon profile picture

CSS in JS

When I first heard of this idea, I was shocked. For decades the best practice was to separate the HTML, CSS and JS concerns. You know, so you can just change the CSS and no need to touch the HTML and JS, right? I guess we all found out at some stage this isn’t true in real projects.

React came and injected HTML into our JS with JSX. The next phase is injecting CSS into JS as well.

Here’s why I think it could be the right way to go:

  1. A more powerful CSS. LESS/SASS were invented to add capabilities to CSS by compiling a new programming language to CSS. Using JS instead of LESS/SASS gives us the same language we know which is more powerful than the others.
  2. Components. JS with React uses components and CSS in JS makes it simple to add specific CSS to a component. The question of “Where should I write these CSS rules and how to scope them?” simply goes away — the styling is in the component itself. As an added bonus, sharing this module is zero dependency with no need to add a <link> tag to a css file.
  3. Less styling code. Adding new CSS is scary — you never know what will change. So you add more CSS which is scoped. Keeping your styling in JS should lead to fewer styling code.
  4. DRY. Many times the JS code needs access to information written in the CSS files (sizes, colors, etc…). Now it’s all JS so you never end up writing the same values in a CSS and a JS file.
  5. Developer Experience. If you already have HMR set up — you’re in for a treat as changes to the CSS (inside JS) are hot reloaded into the browser, no need for a reload.
  6. Gradual implementation. There’s no need for a 100% change in your codebase. You can introduce this alongside regular CSS files.

I currently chose glamor for the job. I really enjoy the API and it’s fast. I’m sure there will be more advancements in this area. The future of CSS finally takes an exciting path.