CSS-in-JS Problems and Solutions
What is CSS-in-JS?
CSS-in-JS is an approach to component styling where CSS is written directly in JavaScript files, often using libraries like styled-components, emotion, linaria, stitches and others.
This approach provides several advantages: scoped styles, dynamic styles, isolation, theme support, etc.
But it also has drawbacks, especially if used without understanding the pitfalls.
Main CSS-in-JS Problems and Solutions
Performance Loss on Render
Every time a component renders, the library may recreate classes or styles. This is especially critical in large lists or with frequent UI updates.
Solution:
- Use static styles when possible.
- Wrap components in
React.memo/useMemo. - Some libraries (e.g., Emotion) have
cssfunctions for caching.
Increased Bundle Size
CSS-in-JS libraries add their runtime to the JavaScript bundle, especially if used without optimizations.
Solution:
- Use Zero-runtime libraries such as:
vanilla-extractastroturflinaria
- Or use compilation at build time (
babel plugin,babel macro,vite plugin,webpack loader).
SSR Problems
CSS-in-JS can cause hydration issues or missing styles on first render.
Solution:
- Use proper SSR setup
- Configure server-side style extraction
- Use libraries with good SSR support
Recommendation:
Choose CSS-in-JS libraries wisely considering your project requirements and performance constraints.