Andrew's Digital Garden

Basics of CSS-in-JS

A quick look at the pros, cons, etc.

Pros

  1. Locally-scoped styles This both helps write styles that don't accidentally 'bleed' out of your target component. Additionally, it helps with maintenance due to colocation.

  2. Colocation Your CSS is next to the thing that consumes the CSS. If you no-longer need the component, it's easily to delete the CSS too. This is massive for refactors, as it prevents dead code from sticking around and make refactors much easier. [[20220801120838-css-explicit-dependencies]] [[20221024115442-colocation]]

  3. Javascript variables in styles Javascript variables are easily referenced in styles. In React, you can pass a colour prop, and immediately pass that to a color CSS rule.

  4. Ability to automatically optimise Dead code elimination, loading CSS only when it's needed, atomic CSS, etc. All of these are easier in CSS-in-JS. [[20220912113924-dead-code-elimination]]

  5. Package management, e.g. sharing CSS Makes it easier to share CSS with each other, as we're effectively just sharing JS again. It also makes it easier to bundle CSS with something like a [[designsystem]], although something like [[20211129113357-cascade-layers]] may help with this in the future. This is a lot bigger when it comes to cross-cutting libraries in big organisations, dealing with versioning, etc.

Cons

Most of the cons of CSS-in-JS simply boil down to performance. Browsers are good at applying CSS on a page through a CSS file and class names. Browsers are worse at applying CSS through JS.

  1. Runtime overhead As a component renders, a CSS-in-JS library must serialise the styles into plain CSS.

  2. Bundle size More modules, more bundle size.

  3. Browser rendering When re-rendering things, the browser needs to figure out what CSS rules to apply. In something like [[20220912123929-concurrent-react]], this can mean recalculating all CSS rules against all DOM nodes, which is slow

  4. SSR is harder The CSS-in-JS library needs to be loaded on the server, and then also handled on the client. This can run into issues with style ordering, running multiple instances of the library, etc.

https://medium.com/seek-blog/a-unified-styling-language-d0c208de2660 https://dev.to/srmagura/why-were-breaking-up-wiht-css-in-js-4g9b

[[api]] [[css]] [[cssinjs]] [[js]] [[performance]]

Basics of CSS-in-JS