DEV Community

TK
TK

Posted on • Updated on

What is CSS in JS?

Click here to read the article in Japanese:https://zenn.dev/takuyakikuchi/articles/b1b20f65d4f9cf

What is CSS in JS?

This approach uses JavaScript to write CSS.

CSS is defined in components, which are independent of external CSS files.

The following example is styling with styled-component.
(Cited from: https://styled-components.com)

const Button = styled.a`
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  width: 11rem;
  background: transparent;
  color: white;
  border: 2px solid white;

  ${props => props.primary && css`
    background: white;
    color: black;
  `}
`

render(
  <div>
    <Button
      href="https://github.com/styled-components/styled-components"
      target="_blank"
      rel="noopener"
      primary
    >
      GitHub
    </Button>

    <Button as={Link} href="/docs">
      Documentation
    </Button>
  </div>
)
Enter fullscreen mode Exit fullscreen mode

The result is the following BUTTON.

code-output

Major CSS in JS

What is good about CSS in JS?

The following is a list of typical advantages of CSS in JS.

  • Encapsulation
  • Maintainability

When using global CSS, it is difficult to know where the CSS definition is affected when it is changed, so it is necessary to address this in the CSS design, such as CSS selector hierarchy and naming conventions.

CSS in JS eliminates the need for detailed CSS design because the impact is confined to components.

  • Dynamic styling
  • Various convenience features provided by the library
    • Automatic insertion of vendor prefixes
    • Nested selectors like Sass are also possible

Because CSS is generated at runtime, styling can be done based on complex logic in JavaScript, such as dynamic styling using JavaScript props.

Also, DX can be improved by using convenient functions provided by the library. (This comes with a learning cost, though.)

  • CSS static analysis

In CSS and Sass, if a class name is incorrect, it cannot be noticed until it is executed.

Also, unused styles cannot be detected by static analysis.

CSS in JS can easily detect unused CSS with static analysis tools for JavaScript such as ESLint and TypeScript compilers, making it easier to find and fix bugs.

  • Portability

Having styles and components in the same file makes it easy to use those components in other projects.

What is not good about CSS in JS?

Below are the typical disadvantages of CSS in JS, but since performance is the biggest point, we will discuss it in a separate section.

  • Poor readability
    • Problem of not knowing which are styled-components
    • Class names are unreadable 例:
<li href="/blog/ecl19xgcapo" class="sc-iqseJM jtAoBP">... </li>
Enter fullscreen mode Exit fullscreen mode
  • Learning Cost (depending on library)

There is a learning cost because the CSS in JS notation is unique and each library has its own way of writing it.

Performance

With conventional CSS, when a web page is loaded, the browser just loads and applies the CSS, so there is little load on the site.

CSS in JS, on the other hand, parses CSS defined in JavaScript and creates JSX elements mapped to CSS.

The browser dynamically generates CSS style tags, which are then read and applied to the web page. This reading and generation takes performance time. (Dual parsing)

  1. Once parsed by the library
  2. Then, parsed by the browser the next time the style is inserted

*If you care about site load performance, runtime CSS-in-JS is not the best solution. *

Zero Runtime CSS in JS

The solution to the above loss of performance time due to double parsing is "Zero-Runtime".

Zero-runtime" refers to CSS in JS, which creates styles using *CSS-in-JS syntax, but generates .css files like those generated by other CSS preprocessors. *

CSS is extracted from the CSS in JS code at build time, and the browser reads these styles and applies them to the web page, saving runtime that would normally be wasted in generating the final style tags.

** Especially useful for large or complex projects where performance is critical. **

performance-comparison
Comparison of performance of initial style injections as components are rendered.
(image source: https://stitches.dev/docs/benchmarks)

Major Zero-run-time CSS in JS.

Summary

result-in-the-state-of-css-2021

CSS in JS is in wide use today, as it is known that styled-components took the top spot in usage in The State of CSS 2021: CSS-in-JS.

The rise of zero-runtime CSS in JS, which improves on the performance disadvantages, is something to keep an eye on in the future.

References

Top comments (2)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Hi Tayuka, keep in mind that benchmarking those things is always subjective to the specific use-case/s tested and the client machine running them. They may differ on different circumstances.

By the way, we use caching to prevent those things to happen. If you need SEO (which is the main reason for bothering around a difference of few miliseconds if you want to be as near as possible from the 100 in core web vitals performance metrics) you can work with Next JS or similar frameworks using SSR or SSG and solve (totally or partially) the "issue" while using styled-components.

In my experience, styled-components end up performing better just because without it, people mess it up with CSS during the development or maintenance of the project 😂

Collapse
 
takuyakikuchi profile image
TK

Thanks for your comment @joelbonetr !

people mess it up with CSS during the development or maintenance of the project 😂

Yeah, you are right!
It is not wise to consider performance from only one angle.