Skip to content

Instantly share code, notes, and snippets.

@dereckmezquita
Last active October 17, 2023 15:00
Show Gist options
  • Save dereckmezquita/ba9f1ccf7b78616e5e39b933e02866f7 to your computer and use it in GitHub Desktop.
Save dereckmezquita/ba9f1ccf7b78616e5e39b933e02866f7 to your computer and use it in GitHub Desktop.
Fix FOUC in Nextjs/React using only styled-components; pre-render and inject css.
import Document from "next/document";
import { ServerStyleSheet } from "styled-components";
import { DocumentContext } from "next/document"; // Importing DocumentContext for TypeScript
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
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();
}
}
}
@dereckmezquita
Copy link
Author

Fixed FOUC issue in my Next.js project by overriding getInitialProps in my _document.tsx file. This allowed me to collect and inject the styles generated by styled-components before each page is loaded, ensuring a smooth rendering without a flash of unstyled content. Additionally, ensuring Server-Side Rendering (SSR) support proved crucial in resolving this issue, making styled-components work seamlessly with Next.js and TypeScript in my setup.

https://dev.to/rashidshamloo/using-styled-components-with-nextjs-v13-typescript-2l6m#:~:text=1,optional

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment