FOUC fix for next.js apps

Posted by Stephen Petrey on Wednesday, May 19, 2021

Next.js is super duper dope. Versatile. Fast. Easy to understand and a dead-simple configuration. What’s not to love? Out-of-the-box, it seems to just work. Pair it with GraphQL and it’s game over. Nothing seems to compare so far in my testing.

My one problem so far, has been FOUC with styled-components. Truly a horrible issue. However, thanks to this bloke, there’s an easy solution.

First create a _document.js file in your pages directory. Assuming you are working with styled-components, drop this in there:

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();
    }
  }
}

That’s literally it! Rebuild your app, and serve and he FOUC issue should be resolved!

Discussion

Leave a Comment