CSS-in-JS is inevitable

June 6th, 2020

Colin McDonnell


The history of web development is a story of replacing blobs of text with structured code.

HTML templates became React component hierarchies. SQL queries became ORM methods (in some cases...). And soon, class-based CSS will be replaced by component-scoped styles defined as JavaScript data structures.

Of course, if you're philosophically opposed to React or ORMs, you'll disagree with this. But in the average case, these either are (or are swiftly becoming) best practices for UI declarations and database interactions.

You shouldn't be responsible for making sure the class names in your HTML also exist in your stylesheets. You shouldn't have to check CSS for typos. You shouldn't have to worry about CSS specificity and class name collisions. You shouldn't have to go hunting for the CSS associated with a given class. Your tooling should do all of that — and it already can if you're using the right library.

It seems likely that object-based declarations ({ fontSize: '12pt' }) will win out long-term, since they're easier to typecheck, generate, and compose (spread operator, anyone?). But tagged template literals (css`font-size: 12pt;`) will have their day in the sun in the interim as people look for ways to re-use vanilla CSS from other projects.

The benefits of defining styles as data structures in a high-level programming language are clear. Developers have consistently chosen the tooling that highlights their syntax, statically analyzes their code, reduces boilerplate, allows scriptability, and catches bugs for them.

This won't play out any differently.

When I write a new blog post, I send it out to my email newsletter a day before I publish it online. I like getting feedback from smart, thoughtful readers before (git) pushing my fledgling posts out of the nest. If you use one of my libraries or like my writing, consider joining!

Future projects will likely involve the PERN+T stack (Postgres, Express, React, Node, plus TypeScript) and some auxiliary technologies. But I reserve the right to publish unintelligible screeds about GraphQL or startups if I want. I post roughly once a month. 🙃

© Colin McDonnell 2020

Colin McDonnell's RSS FEED