Fixing a FOUC when using styled-components with nextjs
February 16th, 2023

Problem

Note: this post is valid as of Next 13 (not beta).

A FOUC is a Flash of Unstyled Content. This happens when the content is loaded before the stylesheets, which results in a brief period of plain unstyled content.

This can happen when using styled-components inside of nextjs.

Fix

To fix this issue, _document.js needs to be updated to override getInitialProps. A couple of helper functions from styled-components allow us to collect the styles generated by styled-components and to inject them before each page is loaded.

Example in javascript:

import Document from "next/document"; import { ServerStyleSheet } from "styled-components"; export default class MyDocument extends Document { static async getInitialProps(ctx) { const sheet = new ServerStyleSheet(); const originalRenderPage = ctx.renderPage; try { ctx.renderPage = () => originalRenderPage({ enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />), }); const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: [initialProps.styles, sheet.getStyleElement()], }; } finally { sheet.seal(); } } }

If using typescript, the type of ctx above is DocumentContext which can be imported from next/document. Example: import {DocumentContenxt} from "next/document".