UN

universal-theme

A unified approach to theme management for web and mobile using CSS color-scheme, React context, and system preference detection.

Install

mkdir -p .claude/skills/universal-theme && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/6395" && unzip -o skill.zip -d .claude/skills/universal-theme && rm skill.zip

Installs to .claude/skills/universal-theme

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Configure light/dark/system theme handling across iOS, Android, and Web with universal CSS
90 charsno explicit “when” trigger
Advanced

Key capabilities

  • Injects theme synchronization scripts
  • Manages system preference CSS variables
  • Persists theme state across sessions
  • Synchronizes theme between browser tabs

How it works

It implements an inline script that checks system-level `color-scheme` before the page paints, then binds React context to persist manual user overrides.

Inputs & outputs

You give it
Configure dark mode or sync theme
You get back
React context provider and CSS variable definition

When to use universal-theme

  • Implementing dark mode toggle
  • Syncing themes across browser tabs
  • Handling system preference changes
  • Preventing theme flicker on page load

About this skill

Universal Theme Handling for Expo

This guide covers implementing proper light/dark/system theme handling across all platforms while respecting web static rendering. This is specifically for projects using universal CSS (Tailwind v4 + react-native-css).

Overview

The approach uses:

  • CSS color-scheme - For automatic system preference detection via prefers-color-scheme
  • CSS classes (.light/.dark) - For manual theme override (shadcn/ui pattern)
  • React Native Appearance API - For native platform theme control
  • ThemeContextProvider - Unified React context for theme state management
  • ThemeScript - Inline script to prevent flash of incorrect theme (FOUC) on page load
  • localStorage persistence - Theme preference persists across sessions
  • Cross-tab sync - Theme changes sync across browser tabs

CSS Setup

Theme Control in CSS

Update your CSS file (e.g., src/css/sf.css) to use color-scheme for automatic system preference detection:

@layer base {
  /*
   * Theme handling with light-dark() CSS function
   * https://lightningcss.dev/transpilation.html#light-dark
   *
   * By default, use "light dark" which enables automatic switching based on
   * prefers-color-scheme media query (system preference).
   *
   * Use .light or .dark class on html/body to force a specific theme.
   * This follows the shadcn/ui pattern for theme control.
   */
  html {
    color-scheme: light dark;
  }

  /* Force light mode when .light class is applied */
  html.light,
  .light {
    color-scheme: light;
  }

  /* Force dark mode when .dark class is applied */
  html.dark,
  .dark {
    color-scheme: dark;
  }
}

Using light-dark() for Colors

Define CSS variables that automatically switch based on the resolved color scheme:

:root {
  /* Colors automatically switch based on color-scheme */
  --sf-text: light-dark(rgb(0 0 0), rgb(255 255 255));
  --sf-bg: light-dark(rgb(255 255 255), rgb(0 0 0));
  --sf-blue: light-dark(rgb(0 122 255), rgb(10 132 255));
}

When color-scheme: light dark is set (system mode), light-dark() responds to the user's system preference automatically via prefers-color-scheme media query.

Theme Context Provider

Create a theme context that manages light/dark/system modes across platforms.

Types

// src/components/ui/theme-context.tsx

/**
 * Theme mode values:
 * - "system": Use the system's color scheme (default)
 * - "light": Force light mode
 * - "dark": Force dark mode
 */
export type ThemeMode = "system" | "light" | "dark";

/**
 * Resolved theme is always either "light" or "dark"
 */
export type ResolvedTheme = "light" | "dark";

interface ThemeContextValue {
  /** The current theme mode setting (system/light/dark) */
  mode: ThemeMode;
  /** The resolved theme based on mode and system preference */
  resolvedTheme: ResolvedTheme;
  /** Set the theme mode */
  setMode: (mode: ThemeMode) => void;
  /** Whether the resolved theme is dark */
  isDark: boolean;
}

localStorage Persistence

Persist theme preference to localStorage so it survives page reloads:

const STORAGE_KEY = "theme-mode";

function getStoredTheme(): ThemeMode | null {
  if (process.env.EXPO_OS !== "web") return null;
  try {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored === "light" || stored === "dark" || stored === "system") {
      return stored;
    }
  } catch {
    // localStorage unavailable
  }
  return null;
}

function saveTheme(mode: ThemeMode): void {
  if (process.env.EXPO_OS !== "web") return;
  try {
    localStorage.setItem(STORAGE_KEY, mode);
  } catch {
    // localStorage unavailable
  }
}

Transition Disabling (borrowed from next-themes)

Temporarily disable CSS transitions during theme changes to prevent jarring animations:

function disableTransitions(): () => void {
  if (process.env.EXPO_OS !== "web") return () => {};

  const style = document.createElement("style");
  style.appendChild(
    document.createTextNode(
      "*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}"
    )
  );
  document.head.appendChild(style);

  return () => {
    // Force a reflow to ensure transitions are disabled before cleanup
    (() => window.getComputedStyle(document.body))();
    setTimeout(() => {
      document.head.removeChild(style);
    }, 1);
  };
}

Web Theme Application

On web, apply .light or .dark classes to the <html> element. For system mode, remove both classes to let CSS handle it via prefers-color-scheme:

function applyWebTheme(mode: ThemeMode, disableAnimations = false): void {
  if (process.env.EXPO_OS !== "web") return;

  const enableTransitions = disableAnimations ? disableTransitions() : null;

  const html = document.documentElement;

  // Remove existing theme classes
  html.classList.remove("light", "dark");

  // Apply appropriate class based on mode
  if (mode === "light") {
    html.classList.add("light");
  } else if (mode === "dark") {
    html.classList.add("dark");
  }
  // For "system" mode, no class is needed - CSS will use prefers-color-scheme

  enableTransitions?.();
}

Native Theme Application

On iOS and Android, use React Native's Appearance.setColorScheme() API:

import { Appearance, ColorSchemeName } from "react-native";

function applyNativeTheme(mode: ThemeMode): void {
  if (process.env.EXPO_OS === "web") return;

  // Map theme mode to ColorSchemeName (null = system)
  const colorScheme: ColorSchemeName = mode === "system" ? null : mode;

  if (process.env.EXPO_OS === "ios") {
    // On iOS, delay slightly to allow for smooth animations
    setTimeout(() => {
      Appearance.setColorScheme(colorScheme);
    }, 100);
  } else {
    // On Android, apply immediately
    Appearance.setColorScheme(colorScheme);
  }
}

Full Context Provider Implementation

import React, {
  createContext,
  useState,
  useEffect,
  useCallback,
  useMemo,
  use,
} from "react";
import { Appearance, ColorSchemeName, useColorScheme } from "react-native";

const ThemeContext = createContext<ThemeContextValue | null>(null);

export function useTheme(): ThemeContextValue {
  const context = use(ThemeContext);
  if (!context) {
    throw new Error("useTheme must be used within a ThemeContextProvider");
  }
  return context;
}

interface ThemeContextProviderProps {
  children: React.ReactNode;
  /** Initial theme mode, defaults to "system" */
  defaultMode?: ThemeMode;
}

export function ThemeContextProvider({
  children,
  defaultMode = "system",
}: ThemeContextProviderProps) {
  // Initialize from localStorage on web, otherwise use defaultMode
  const [mode, setModeState] = useState<ThemeMode>(() => {
    if (process.env.EXPO_OS === "web") {
      return getStoredTheme() ?? defaultMode;
    }
    return defaultMode;
  });

  // Get the current system color scheme
  const systemColorScheme = useColorScheme();

  // Resolve the actual theme based on mode and system preference
  const resolvedTheme: ResolvedTheme = useMemo(() => {
    if (mode === "system") {
      return systemColorScheme === "dark" ? "dark" : "light";
    }
    return mode;
  }, [mode, systemColorScheme]);

  const isDark = resolvedTheme === "dark";

  // Apply theme when mode changes
  const setMode = useCallback((newMode: ThemeMode) => {
    setModeState(newMode);
    saveTheme(newMode);

    if (process.env.EXPO_OS === "web") {
      // Disable transitions when user explicitly changes theme
      applyWebTheme(newMode, true);
    } else {
      applyNativeTheme(newMode);
    }
  }, []);

  // Apply initial theme on mount
  useEffect(() => {
    if (process.env.EXPO_OS === "web") {
      applyWebTheme(mode);
    } else {
      applyNativeTheme(mode);
    }
  }, []);

  // Cross-tab synchronization via storage events (web only)
  useEffect(() => {
    if (process.env.EXPO_OS !== "web") return;

    const handleStorage = (e: StorageEvent) => {
      if (e.key !== STORAGE_KEY) return;

      const newMode = e.newValue as ThemeMode | null;
      if (newMode === "light" || newMode === "dark" || newMode === "system") {
        setModeState(newMode);
        applyWebTheme(newMode, true);
      } else {
        // Invalid or cleared - reset to default
        setModeState(defaultMode);
        applyWebTheme(defaultMode, true);
      }
    };

    window.addEventListener("storage", handleStorage);
    return () => window.removeEventListener("storage", handleStorage);
  }, [defaultMode]);

  const value = useMemo(
    () => ({
      mode,
      resolvedTheme,
      setMode,
      isDark,
    }),
    [mode, resolvedTheme, setMode, isDark]
  );

  return <ThemeContext value={value}>{children}</ThemeContext>;
}

Theme Provider with React Navigation

Wrap the theme context with React Navigation's theme provider for proper navigation theming:

// src/components/ui/theme-provider.tsx
import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider as RNTheme,
} from "@react-navigation/native";
import { ThemeContextProvider, useTheme, ThemeScript } from "./theme-context";

// Re-export for convenience
export { useTheme, ThemeScript } from "./theme-context";
export type { ThemeMode, ResolvedTheme } from "./theme-context";

function NavigationThemeProvider({ children }: { children: React.ReactNode }) {
  const { isDark } = useTheme();
  return (
    <RNTheme value={isDark ? DarkTheme : DefaultTheme}>{children}</RNTheme>
  );
}

export default function ThemeProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <ThemeContextProvider defaultMode="system">
      <NavigationThemeProvider>{children}</NavigationThemeProvider>
    </ThemeContextProvider>
  );
}

Preventing Flash of Incorrect Theme (FOUC)

On page load, there can be a brief flash where the wrong the


Content truncated.

When not to use it

  • Projects not requiring cross-platform theme parity
  • Systems relying solely on server-side rendering

Prerequisites

Tailwind v4React context

Limitations

  • Requires Tailwind v4+ configuration
  • Platform-specific CSS handling required for native mobile
  • LocalStorage dependency

How it compares

It solves the 'flash of unstyled content' (FOUC) problem programmatically, ensuring the theme is consistent before hydration.

Compared to similar skills

universal-theme side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
universal-theme (this skill)17moReviewAdvanced
ui-ux-pro-max1,9095moReviewIntermediate
ui-styling129moReviewBeginner
elegant-design215moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

ui-ux-pro-max

nextlevelbuilder

UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient.

1,9092,023

ui-styling

mrgoonie

Create beautiful, accessible user interfaces with shadcn/ui components (built on Radix UI + Tailwind), Tailwind CSS utility-first styling, and canvas-based visual designs. Use when building user interfaces, implementing design systems, creating responsive layouts, adding accessible components (dialogs, dropdowns, forms, tables), customizing themes and colors, implementing dark mode, generating visual designs and posters, or establishing consistent styling patterns across applications.

12132

elegant-design

rand

Create world-class, accessible, responsive interfaces with sophisticated interactive elements including chat, terminals, code display, and streaming content. Use when building user interfaces that need professional polish and developer-focused features.

21108

web-design-reviewer

github

This skill enables visual inspection of websites running locally or remotely to identify and fix design issues. Triggers on requests like "review website design", "check the UI", "fix the layout", "find design problems". Detects issues with responsive design, accessibility, visual consistency, and layout breakage, then performs fixes at the source code level.

750

design-lab

0xdesign

Conduct design interviews, generate five distinct UI variations in a temporary design lab, collect feedback, and produce implementation plans. Use when the user wants to explore UI design options, redesign existing components, or create new UI with multiple approaches to compare.

735

frontend-design-pro

claudekit

Creates jaw-dropping, production-ready frontend interfaces AND delivers perfectly matched real photos (Unsplash/Pexels direct links) OR flawless custom image-generation prompts for hero images, backgrounds, and illustrations. Zero AI slop, zero fake URLs.

1011

Search skills

Search the agent skills registry