Since the release of React 18, many CSS-in-JS libraries like styled-components, emotion, and stitches have encountered a significant challenge. They generate CSS only at runtime, making them incompatible with streaming and React Server Components. React developers have addressed this issue in an article, where they explicitly advise against using CSS-in-JS libraries that generate CSS at runtime.
This has created substantial uncertainty among developers and the communities of these affected libraries. The question arises: Is it possible to refactor these runtime libraries into buildtime libraries? To date, none of the libraries have announced any such plans, and, unfortunately, one of the most popular new libraries, stitches, is no longer being maintained.
Fortunately, there has been a growing number of CSS-in-JS solutions that generate CSS at buildtime. Libraries like Vanilla Extract, panda, and Kuma UI maintain an excellent developer experience, overcome performance disadvantages, and are compatible with React 18.
Unfortunately, these libraries are not yet widely adopted, and it's challenging to predict how they will develop in the future. Therefore, at DCX, we continue to use established solutions as long as the new React features are not mandatory.
Moreover, we are gaining experience with these new libraries because we see significant potential in them.
CSS-in-JS is a method where JavaScript is used to style components. The first libraries which implemented this technique were Styled-Components, Emotion & JSS.
Example:
const Button = styled.button`
display: inline-block;
padding: 0.5rem 0;
background: transparent;
color: white;
border: 2px solid white;
${(props) =>
props.primary &&
css`
background: white;
color: black;
`}
`;
return <Button primary>Click me</Button>;
Advantages of CSS-in-JS
- Local scoping instead of global namespace
- No classname to element mapping
- Use the full power of JavaScript to enhance CSS (loops, variables & more)
- Dynamic styling & theming (access to state or props)
- TypeScript support
Disadvantages of CSS-in-JS
- Runtime cost when using dynamic styling
- Slightly different syntax than traditional CSS (object syntax vs template literals)
- Can add an extra layer of complexity
In the meantime CSS-in-JS has evolved even more. There are some libraries which leverages nearly zero-runtime costs such as Stitches or Vanilla Extract while still providing an excellent developer experience with TypeScript.
We at DCX think that CSS-in-JS is the future of writing good, performant and maintainable CSS, therefore we already use different CSS-in-JS solutions throughout multiple applications.