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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source