@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/corewithout the fulltheme-uipackage - Need fine-grained control over color mode behavior
theme-ui package which includes this package.
Exports
Components
ColorModeProvider
A React component that provides color mode functionality to your application.
- 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
children:React.ReactNode- Child components
InitializeColorMode
A script component that prevents flash of unstyled content (FOUC) when loading the page.
- 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.
ColorModeProvider.
Context Extensions
The package extends the Theme UI context with color mode properties: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:Multiple Color Modes
Support more than just light and dark:Nested Color Modes
NestedColorModeProvider 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
TheInitializeColorMode component injects this script:
TypeScript Types
Notes
- Requires
@theme-ui/coreand@theme-ui/cssas dependencies - Requires
@emotion/reactand 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
Related
- @theme-ui/core - Core Theme UI functionality
- Color Modes guide - Full color modes documentation
- Theming - Theme configuration
