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)
npm install styled-components(v6).next.config.ts:compiler: { styledComponents: true }.- Create
lib/registry.tsx("use client") that creates aServerStyleSheet, usesuseServerInsertedHTMLto flush styles into the HTML stream, and wraps children inStyleSheetManageron the server. - Wrap
{children}in the root layout with<StyledComponentsRegistry>. - Any component that uses
styledmust 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
1// lib/registry.tsx2"use client";34import { useState } from "react";5import { useServerInsertedHTML } from "next/navigation";6import { ServerStyleSheet, StyleSheetManager } from "styled-components";78export default function StyledComponentsRegistry({ children }: { children: React.ReactNode }) {9 const [sheet] = useState(() => new ServerStyleSheet());1011 useServerInsertedHTML(() => {12 const styles = sheet.getStyleElement();13 sheet.instance.clearTag();14 return <>{styles}</>;15 });1617 if (typeof window !== "undefined") return <>{children}</>;18 return <StyleSheetManager sheet={sheet.instance}>{children}</StyleSheetManager>;19}2021// app/layout.tsx22// <body><StyledComponentsRegistry>{children}</StyledComponentsRegistry></body>2324// app/button.tsx25// "use client";26// import styled from "styled-components";27// export const Button = styled.button`padding: 8px 16px; border-radius: 8px;`;2829// 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.