Skip to main content
The @theme-ui/color-modes package provides utilities for managing color modes in Theme UI applications. It handles color mode state, localStorage persistence, and system preference detection.

Installation

This package is included in the main theme-ui package and generally should not be used on its own. It’s automatically imported when you use theme-ui.

When to Use

This package is used internally by Theme UI. You would only install it directly if you’re:
  • Building a custom Theme UI setup
  • Using @theme-ui/core without the full theme-ui package
  • Need fine-grained control over color mode behavior
For most use cases, use the theme-ui package which includes this package.

Exports

Components

ColorModeProvider

A React component that provides color mode functionality to your application.
Features:
  • Manages color mode state
  • Persists selection to localStorage
  • Syncs with system color scheme preferences
  • Applies color mode colors to theme
  • Generates CSS custom properties for color modes
Props:
  • children: React.ReactNode - Child components

InitializeColorMode

A script component that prevents flash of unstyled content (FOUC) when loading the page.
This component injects a small script that:
  • Reads the color mode from localStorage
  • Applies it to the document before React hydrates
  • Prevents flashing between color modes on page load

Hooks

useColorMode

A React hook to access and control the current color mode.
Returns:
TypeScript:
Error: Throws an error if used outside of a ColorModeProvider.

Context Extensions

The package extends the Theme UI context with color mode properties:
Access these through useThemeUI() from @theme-ui/core:

Configuration

Configure color modes in your theme:

Features

localStorage Persistence

By default, color mode selection is persisted to localStorage:

System Preference Detection

Automatically detect and follow system color scheme:

CSS Custom Properties

Colors are converted to CSS custom properties for efficient switching:
Disable with:

Multiple Color Modes

Support more than just light and dark:

Nested Color Modes

Nested ColorModeProvider components are supported for section-specific color modes.

Implementation Details

Storage Key

Color mode is stored in localStorage under the key:

Media Queries

The package uses these media queries for system preference:

FOUC Prevention

The InitializeColorMode component injects this script:
This runs before React hydration to apply the correct color mode immediately.

TypeScript Types

Notes

  • Requires @theme-ui/core and @theme-ui/css as dependencies
  • Requires @emotion/react and React 18+ as peer dependencies
  • No side effects - safe for tree-shaking
  • Supports server-side rendering with FOUC prevention
  • Works with nested theme providers

Examples

Basic Toggle

Multiple Mode Selector

With Icon