Overview
InitializeColorMode is a component that prevents a flash of unstyled content (FOUC) when using server-side rendering (SSR). It injects a small script that runs before React hydration to apply the correct color mode class immediately.
Import
Usage
In a Custom Document (Next.js)
For Next.js applications, addInitializeColorMode to your custom _document.js or _document.tsx file:
pages/_document.tsx
In a Custom HTML Template (Gatsby)
For Gatsby applications, add it to yourhtml.js file:
html.js
In a Custom HTML File
For other frameworks, you can manually add the script to your HTML:index.html
How It Works
InitializeColorMode renders a <script> tag that:
- Reads the stored color mode from localStorage using the key
theme-ui-color-mode - Adds a class to the document element in the format
theme-ui-{mode}(e.g.,theme-ui-dark) - Runs synchronously before React hydration to prevent visual flashing
The Injected Script
The component injects the following script:Why Is This Needed?
WithoutInitializeColorMode, here’s what happens during SSR:
- Server renders HTML with default color mode
- Browser displays the server-rendered HTML (default mode)
- React hydrates and reads the user’s preferred mode from localStorage
- Color mode updates, causing a visible flash
InitializeColorMode solves this by applying the correct color mode before the page renders, eliminating the flash.
Important Notes
Place
InitializeColorMode in the <head> of your document for best results. It must run before the page renders.- The script is wrapped in a try-catch block to handle cases where localStorage is disabled
- If no color mode is stored in localStorage, the script does nothing
- The class added by this script is removed by the
ColorModeProviderafter React hydration - The script is minimal (< 200 bytes) and has no dependencies
When to Use
UseInitializeColorMode when:
- You’re using server-side rendering (SSR)
- You’re using static site generation (SSG)
- You want to prevent flash of unstyled content (FOUC)
- You’re using
useLocalStoragein your theme config (enabled by default)
InitializeColorMode when:
- You’re building a client-only application
- You’ve disabled
useLocalStoragein your theme config - You’re not using color modes in your application
