DeployU
Interviews / Frontend Engineering / How do you do styling in Next.js?

How do you do styling in Next.js?

conceptual Styling Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are building a new component that needs to have some custom styles.

You are not sure which of the different ways to do styling in Next.js you should use.

The Challenge

Explain the different ways to do styling in Next.js. What are the pros and cons of each approach, and which one would you choose for this use case?

Wrong Approach

A junior engineer might just use a global stylesheet for everything. This would not be a very scalable or maintainable solution.

Right Approach

A senior engineer would know that there are several different ways to do styling in Next.js. They would be able to explain the pros and cons of each approach and would have a clear recommendation for which one to use in a given situation.

Step 1: Understand the Different Ways to Do Styling

MethodDescription
Global StylesA global stylesheet that is applied to the entire application.
CSS ModulesA CSS file in which all class names and animation names are scoped locally by default.
Styled-JSXA CSS-in-JS library that is built into Next.js.
CSS-in-JS LibrariesLibraries like Emotion and Styled Components.

Step 2: Choose the Right Tool for the Job

Use CaseRecommended Method
A simple application with a few pagesGlobal Styles
A component libraryCSS Modules
A large application with many componentsCSS-in-JS Libraries

For our use case, we should use CSS Modules. This is because we are building a new component that needs to have its own custom styles, and we want to make sure that the styles are scoped locally to the component.

Step 3: Code Examples

Here are some code examples that show the difference between the different approaches:

Global Styles:

// pages/_app.js
import '../styles.css'

export default function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

CSS Modules:

// components/MyComponent.module.css
.my-class {
  color: red;
}

// components/MyComponent.js
import styles from './MyComponent.module.css'

export default function MyComponent() {
  return <div className={styles['my-class']}>Hello, world!</div>
}

Styled-JSX:

export default function MyComponent() {
  return (
    <div>
      <p>Hello, world!</p>
      <style jsx>{`
        p {
          color: red;
        }
      `}</style>
    </div>
  );
}

Practice Question

You are building a component library and you want to make sure that the styles are scoped locally to each component. Which of the following would be the most appropriate?