A script component that prevents flash of unstyled content (FOUC) by applying the user's preferred color mode before the page renders.
Add ColorModeInitializer to your root layout's <head>:
// app/layout.tsx
import { ColorModeInitializer } from "@neynar/ui/color-mode";
import "./globals.css"; // Contains: @import "@neynar/ui/styles"; @import "@neynar/ui/themes/purple-dawn";
export default function RootLayout({ children }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<ColorModeInitializer />
</head>
<body>{children}</body>
</html>
);
}- Reads cookie — Checks for saved
color-modepreference - Checks system — Falls back to
prefers-color-schememedia query - Applies class — Adds
darkorlightclass to<html>element - Runs inline — Executes before page content renders (no FOUC)
- Must be in
<head>— The script needs to run before body content - Use
suppressHydrationWarning— Prevents React hydration mismatch warnings - Zero runtime cost — Just an inline script, no React component overhead
- Works with SSR — Cookie-based for server-side rendering compatibility
The component reads/writes a cookie named color-mode:
{
"preference": "system" | "light" | "dark",
"mode": "light" | "dark"
}preference— What the user selectedmode— The resolved actual mode (for SSR)