Search code examples
reactjsnext.jsproductionfoucmantine

Flash of Unstyled Content (FOUC) for Nextjs using Mantine


I switched to Mantine and followed this approach to solve the FART (Flash of inAccurate coloR Theme), but the webpage runs into a new issue. There is a flash of Unstyled component before the page renders. How to solve this issue? I looked into Nextjs Github and there were issues few FOUC issues, but the solution was to add <script>0</script>, which didn't work for me.

This bug is only in production, in development it works fine.

Example: https://gotrip.vercel.app If you don't see the flash, copy the link and paste it in the browser.

import Document, { Html, Head, Main, NextScript } from "next/document";
import { createGetInitialProps } from "@mantine/next";

const getInitialProps = createGetInitialProps();

export default class _Document extends Document {
    static async getInitialProps(ctx) {
        const initialProps = await Document.getInitialProps(ctx);
        return { ...getInitialProps, ...initialProps };
    }

    render() {
        const setInitialTheme = `
      function getUserPreference() {
        if(window.localStorage.getItem('theme')) {
          return window.localStorage.getItem('theme')
        }
        return window.matchMedia('(prefers-color-scheme: dark)').matches 
          ? 'dark' 
          : 'light'
      }
      document.body.dataset.theme = getUserPreference();
    `;
        return (
            <Html>
                <Head />
                <body>
                    <script dangerouslySetInnerHTML={{ __html: setInitialTheme }} />
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

Solution

  • After going through this Github issue I applied three solutions to my project because I have had similar issues.

    If anybody comes across this issue try the following it should work for you.

    1. If you have not done it configure your Next.js project to work with Mantine using this instruction. (NOTICE: I recommend applying the optional step also)

    2. If you host your project on Vercel or for local development - use "yarn build" instead of npm

    3. Downgrade Next.js to 12.1.5 if you are on 12.1.6 or upgrade to something newer (@canary versions)

    I hope this solves your problem. This is my first answer so be kind :)