CSS Modules

Learn how Next.js includes CSS modules and some pros and cons.

We'll cover the following...

Selection of styling method in Next.js

Previously, we saw a CSS-in-JS library, meaning that we had to write our CSS definitions in JavaScript, transforming those styling rules to plain CSS at runtime or compile time, depending on which library we choose and how we configure it.

While we personally like the CSS-in-JS approach, we eventually recognized that it has some significant drawbacks to consider when choosing the styling method for a new Next.js app.

Many CSS-in-JS libraries don’t provide good IDE/code editor support, making things way harder for developers (no syntax highlighting, autocomplete, linting, and so on). Also, using CSS-in-JS forces us to adopt more and more dependencies, making our application bundle bigger and slower.

Speaking of performance, here’s another big drawback: even if we pre-generate CSS rules on the server side, we would need to regenerate them after React hydration on the client side. That adds a high runtime cost, making the web application slower and slower, and it will only worsen when we add more features to our app.

But here comes an excellent alternative to Styled JSX: CSS modules. Previously, we talked about locally scoped CSS rules and how Styled JSX makes it easy to ...