develop
PublishDate16 Oct 2024
Resolving FOUC in Next.js

While upgrading the Next.js version of my side project, I had to change several libraries and configurations. During the migration process, I noticed that the Next.js website does not provide support for the Emotion library. However, the Emotion website showed how to set up Emotion for SSR in Next.js projects. Given the significant amount of work involved in the migration, I decided to follow the instructions on the Emotion website. If that didn’t work, I would switch back to styled-components.


Unfortunately, despite following the recommended steps, FOUC still occurred. I attempted various troubleshooting methods, including tweaking the cache setup, adjusting how styles were loaded, and even modifying the SSR (Server-Side Rendering) configuration. However, none of these efforts successfully eliminated the problem.


After trying various methods, I decided to migrate from Emotion to styled-components. Styled-components officially support SSR in Next.js. Following the guidance on their website, I applied styled-components, and after completing the transition, the FOUC issue was resolved.


However, I later discovered that styled-components can still cause FOUC when using dynamic styling. In such cases, using next/dynamic with dynamic imports is necessary to prevent the issue. For dynamic styling, disabling SSR (Server-Side Rendering) by utilizing dynamic imports ensures the styles are correctly loaded without causing FOUC.

import dynamic from 'next/dynamic'
const DynamicHeader = dynamic(() => import('../components/header'), {
loading: () => <p>Loading...</p>,
})

This experience taught me that while Emotion is a powerful CSS-in-JS library, it can sometimes lead to challenges with Next.js, particularly when dealing with SSR. By switching to styled-components and applying dynamic imports for dynamic styling, I was able to solve the FOUC issue.

© 2024

Park Gadan

33°06'56.2"-38°34'03.5"