Next.jsMedium

How do you use styled-components in Next.js?

styled-components works in the App Router only inside Client Components, with a style registry that collects styles during server rendering and injects them with useServerInsertedHTML. Enable the SWC transform with compiler.styledComponents: true for SSR-safe class names and better debugging.

Setup (App Router)

  1. npm install styled-components (v6).
  2. next.config.ts: compiler: { styledComponents: true }.
  3. Create lib/registry.tsx ("use client") that creates a ServerStyleSheet, uses useServerInsertedHTML to flush styles into the HTML stream, and wraps children in StyleSheetManager on the server.
  4. Wrap {children} in the root layout with <StyledComponentsRegistry>.
  5. Any component that uses styled must be a Client Component.

Pages Router

Use _document.tsx with getInitialProps and ServerStyleSheet.collectStyles, plus the same compiler option.

Trade-offs

  • Runtime styling adds JavaScript and work during rendering, and cannot be used in Server Components.
  • Styles are injected during streaming; misconfiguration leads to unstyled flashes or hydration mismatches.
  • The library maintainers have said styled-components is in maintenance mode and do not recommend it for new projects.

Recommendation for new projects

Prefer zero-runtime options that work in Server Components: Tailwind CSS, CSS Modules, or compile-time CSS-in-JS such as vanilla-extract, Panda CSS, StyleX or Kuma UI. Keep styled-components for existing codebases while migrating.

Code example

tsx
1// lib/registry.tsx
2"use client";
3
4import { useState } from "react";
5import { useServerInsertedHTML } from "next/navigation";
6import { ServerStyleSheet, StyleSheetManager } from "styled-components";
7
8export default function StyledComponentsRegistry({ children }: { children: React.ReactNode }) {
9 const [sheet] = useState(() => new ServerStyleSheet());
10
11 useServerInsertedHTML(() => {
12 const styles = sheet.getStyleElement();
13 sheet.instance.clearTag();
14 return <>{styles}</>;
15 });
16
17 if (typeof window !== "undefined") return <>{children}</>;
18 return <StyleSheetManager sheet={sheet.instance}>{children}</StyleSheetManager>;
19}
20
21// app/layout.tsx
22// <body><StyledComponentsRegistry>{children}</StyledComponentsRegistry></body>
23
24// app/button.tsx
25// "use client";
26// import styled from "styled-components";
27// export const Button = styled.button`padding: 8px 16px; border-radius: 8px;`;
28
29// next.config.ts: compiler: { styledComponents: true }

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app