Why I Write CSS in JavaScript
Imagine a programming language that only had global variables.<p>You have to carefully name your variables using complicated conventions in order to avoid any conflicts or unexpected behavior.<p>Even your functions don't have local variables; there is no lexical scoping. Any function can overwrite or mutate what any other function is doing inside. There is no real encapsulation.<p>After you've done this perfectly, your application gets bigger and you start wanting to reuse third-party modules made by other developers, because they've already solved some of your problems.<p>Uh-oh: they didn't follow exactly the same conventions, and now things conflict. Or their variable names <i>were</i> perfectly unique in their own code base but not when combined with yours (or when combined with several other third-party modules).<p>This language is CSS and is why people are so fed up with selectors. Even "scoped" selectors really aren't lexically scoped in the sense that other languages handle scoping... it's still just another naming convention hack.<p>I use CSS-in-JS because CSS wasn't designed to be a language that survives attempts at modularization, third-party code sharing, etc. No sane programming language attempting this would only have global variables. So, we throw out the selectors part of CSS and keep the rest, at least for now.<p>Nobody using CSS-in-JS thinks this is an ideal situation. Nobody wakes up thinking, "oh my god, I need to put my CSS in my JS, it would be perfect." We're just trying to deal with the hand that's been dealt.