Unlocking the Power of CSS-in-JS: A Game-Changer for Developers
CSS-in-JS has revolutionized the way developers approach CSS, offering a modular approach with local scoping that makes maintenance a breeze. However, this innovative solution comes with a catch – it can lead to performance issues due to dynamic rendering. But fear not, dear developers! There’s a silver lining to this cloud.
The Problem with CSS-in-JS
When using modern UI libraries like React, browsers wait for the JavaScript bundle file to download before rendering anything on the screen, increasing loading times. This is where First Meaningful Paint (FMP) comes in – a concept coined by Google to measure when the primary content of a page is visible to the user. As React gains popularity, bundle sizes can balloon from 2MB to over 20MB, causing headaches for developers.
Solving the Bundle Size Problem
To combat this issue, developers have created solutions like splitting bundles into chunks or lazy loading apps. But what about CSS-in-JS? This pattern has a similar problem, as browsers need to dynamically generate and update <style>
tags in response to state and prop changes. The fantastic developer experience of writing CSS inside JavaScript files comes at the cost of generating CSS at runtime.
Compiled: The Solution You’ve Been Waiting For
Enter Compiled, a CSS-in-JS library created by Atlassian Labs that provides an excellent developer experience without the runtime cost. It works by statically analyzing code at build time, transforming it into Compiled components, and moving styling code into the head of the document at runtime. Compiled mirrors the styling pattern found in styled-components and Emotion, making it a seamless transition for developers.
How Compiled Works
Below is a simple example of how Compiled transforms code:
Using Compiled with React
To use Compiled with React, install the package and compiler. You can use either Babel or the TypeScript compiler with Compiled. If you’re using Create React App, you’ll need to eject from the bundle and edit the config files to set up both compilers.
Benefits of Compiled
Compiled solves performance issues caused by dynamic CSS generation, allowing developers to enjoy the benefits of CSS-in-JS without sacrificing performance. With Compiled, you can write CSS-in-JS files by importing from the main library, and then import the component. It’s exactly the same CSS-in-JS pattern, but without generating CSS at runtime.
Take Your Development to the Next Level
Discover how Compiled can revolutionize your development workflow. Say goodbye to performance issues and hello to a seamless developer experience.