ADR 011: CSS-in-JS for React components
Status: accepted
Context
React components need encapsulated, dynamic styles, both for maintainability and to adapt to component state and properties. CSS-in-JS attaches styles directly to components.
Decision
React components are styled with CSS-in-JS, using an established library such as Emotion.
Reasons
- Encapsulation. Each component owns its styles, without conflicts with the rest of the application.
- Dynamic styles. Styles change easily with properties or state.
- Theming. CSS-in-JS libraries support themes natively.
- Portability. A component moves or is reused together with its styles.
- No dead styles. Unused styles are removed automatically.
Drawbacks
- Performance. Styles are injected into the page at run time, which can slow the first render of large applications.
- Bundle size. The library adds weight to the JavaScript bundle.
- Debugging. Generated class names make styles harder to trace.
- Separation of concerns. Some teams prefer to keep logic and presentation apart.
- Learning. New developers have another library to learn.
Alternatives considered
| Alternative | For | Against |
|---|---|---|
| CSS Modules | Similar encapsulation, with no run-time cost | Less suited to dynamic styles |
| Utility-first CSS, such as Tailwind CSS | Light and fast, suited to static styles | Styles can be verbose in the markup |
| Plain CSS or Sass | Simple and well known | Style conflicts are hard to manage in large projects |
Consequences
- Component styles live in the React code, which makes components self-contained.
- Performance is monitored, in particular the time to interactive of pages.
- Clear guidelines prevent excessive or inefficient use.
Review
The decision is reviewed after a first implementation on a subset of components, to check its real effect on performance and maintainability. If significant problems appear, CSS Modules will be considered instead.