Demystifying styled-components by Rebuilding It

Joshua Comeau takes a hands-on approach to understanding styled-components by deconstructing its core mechanics and rebuilding them from scratch. The exercise is both practical and illuminating, shedding light on how the popular CSS-in-React library operates under the hood.

styled-components holds a dominant position in the CSS-in-React space, though not everyone has been entirely won over by it. The fundamentals do stand out: scoped styles via unique class names, plus seamless hot module reloading since everything lives in JavaScript. For those already using css-modules, those benefits come standard, alongside file separation and built-in Sass support.

Yet Comeau’s deep dive highlights a few areas where styled-components is starting to make inroads:

  • With css-modules, naming is still required—even if just .root. styled-components attaches styles directly to components, eliminating the need to think up names at all.
  • css-modules styles apply directly to HTML elements only. styled-components can target custom components, applying styles via prop spreading later.
  • Since styles are embedded in JavaScript files, you get full access to JavaScript features—ternaries, prop access, and complex expressions.

It’s a worthwhile read for anyone curious about what’s actually happening behind the scenes in styled-components.

Direct Link →