What is CSS in JS?
Tags: css, webdev, beginners
Published: 2022-07-18 02:04:53

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.<br/>
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)

```js
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>
)
```

The result is the following BUTTON.

![code-output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bd232y0wztvqwuhsh6pn.png)

### Major CSS in JS

- [styled-components](https://styled-components.com/)
- [Emotion](https://emotion.sh/docs/introduction)

## 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.<br/>
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.<br/>
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. <br/>
Also, unused styles cannot be detected by static analysis.<br/>
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
例：
```html
<li href="/blog/ecl19xgcapo" class="sc-iqseJM jtAoBP">... </li>
```

- **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.<br/>
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o2ddq0zt4dr98upt97lk.png)
*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.

- [Linaria](https://linaria.dev/)
- [vanilla-extract](https://vanilla-extract.style/)
- [Stitches](https://stitches.dev/)(Near-zero-run-time)

## Summary


![result-in-the-state-of-css-2021](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/broctrjeverp0aztya7r.png)

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](https://2021.stateofcss.com/en-US/technologies/css-in-js). <br/>
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

- [What is CSS in JS](https://b.0218.jp/202202182358.html)
- [Comparing the top zero-runtime CSS-in-JS libraries - LogRocket Blog](https://blog.logrocket.com/comparing-the-top-zero-runtime-css-in-js-libraries/)
- [The Unseen Performance Costs of Modern CSS-in-JS Libraries | CSS-Tricks - CSS-Tricks](https://css-tricks.com/the-unseen-performance-costs-of-modern-css-in-js-libraries/)