Stoop
GitHub
/

preloadTheme

Preload theme CSS variables before React renders to prevent FOUC (Flash of Unstyled Content)

Usage

import { preloadTheme } from "./theme";

// Injects all themes configured in createStoop
preloadTheme();

Parameters

None. The function injects CSS variables for all themes configured in themes config. Only works when themes config is provided to createStoop.

Preventing FOUC

When loading a non-default theme from localStorage, use preloadTheme() before React renders:

Client Component Approach

"use client";

import { useEffect, type ReactNode } from "react";
import { preloadTheme } from "./theme";

export default function RootLayout({ children }: { children: ReactNode }) {
  useEffect(() => {
    // Preload all themes - Provider will handle theme selection
    preloadTheme();
  }, []);

  return <>{children}</>;
}

Use a script tag for a more robust solution. preloadTheme() must be available in the global scope, which requires exposing your Stoop instance:

// stoop.theme.ts
import { createStoop } from "stoop";

const stoop = createStoop({
  theme: { /* ... */ },
  themes: { /* ... */ },
});

// Expose for script tag usage (optional)
if (typeof window !== "undefined") {
  (window as any).stoopPreloadTheme = stoop.preloadTheme;
}

export const { styled, css, Provider, useTheme, getCssText, preloadTheme } = stoop;
// app/layout.tsx
import Script from "next/script";
import { type ReactNode } from "react";
import { getCssText } from "./stoop.theme";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html>
      <head>
        <style
          id="stoop-styles"
          dangerouslySetInnerHTML={{ __html: getCssText() }}
        />
        <Script
          id="stoop-theme-preload"
          strategy="beforeInteractive"
          dangerouslySetInnerHTML={{
            __html: `
              (function() {
                if (typeof window.stoopPreloadTheme === 'function') {
                  window.stoopPreloadTheme();
                }
              })();
            `,
          }}
        />
      </head>
      <body>{children}</body>
    </html>
  );
}

Note: The Provider handles theme preloading when it mounts, so manual preloadTheme() calls are usually not needed. Call preloadTheme() manually only if you need to preload themes before React renders (e.g., to prevent FOUC when loading theme from localStorage).

Notes