CSS in JS

CSS-in-JS libraries are tools that allow you to write CSS styles directly within your JavaScript code, typically inside React components. They help you style components in a modular, scoped, and dynamic way.

🔧 How They Work:

Instead of using traditional .css or .scss files, CSS-in-JS lets you:

✅ Benefits:

The following libraries are supported in Client Components in the app directory:

To style Server Components, we recommend using CSS Modules, PostCSS or Tailwind CSS.

Setting up CSS-in-JS involves a three-step opt-in process:

  1. Style Registry - Collects all CSS rules during rendering.
  2. useServerInsertedHTML() Hook - Ensures styles are injected before any related content is rendered.
  3. Client Component Wrapper - Wraps your application with the style registry during the initial server-side render.
Next.js automatically sets up styled-jsx with either Babel or SWC, so no manual configuration is needed.
Remember to enable the 'styledComponents' option in next.config.js.

In this way, during server-side rendering, styles are extracted into a global registry and injected into the <head> of the HTML. This ensures that style rules are applied before any related content appears, preventing visual flashes in the UI.

When streaming, styles from each HTML chunk are collected and merged with the existing styles. Once client-side hydration finishes, styled-components resumes control and handles any additional dynamic styling.

A Client Component is placed at the top level of the component tree to manage the style registry efficiently. This approach avoids regenerating styles on subsequent server renders and keeps CSS out of the Server Component payload.