Skip to content

context theme

Paulo Gomes da Cruz Junior edited this page Apr 13, 2026 · 1 revision

🎨 Theme Context

Overview

The ThemeContext provides a centralized mechanism for managing the Carbon Design System theme across the application. It allows components to access the current theme, switch between predefined themes, and update the global theme preference. This context works in tandem with the PreferenceContext to persist user-selected themes across sessions.

Themes are applied using Carbon’s <Theme> component, which wraps the entire app and ensures consistent styling. The context also updates the data-carbon-theme attribute on the root HTML element, enabling theme-specific styling hooks.

🧩 Context API

ThemeContextData

type ThemeContextData = {
  theme: CarbonTheme;
  setTheme: (theme: CarbonTheme) => void;
  toggleTheme: () => void;
};

CarbonTheme

type CarbonTheme = 'white' | 'g10' | 'g90' | 'g100';

🧪 Usage Example

import { useTheme } from '@/context/theme/useTheme';

const ThemeToggleButton = () => {
  const { theme, toggleTheme } = useTheme();

  return (
    <button onClick={toggleTheme}>
      Switch to {theme === 'g10' ? 'Dark' : 'Light'} Theme
    </button>
  );
};

🔍 Implementation Details

  • Initial Theme: Loaded from PreferenceContext to ensure persistence.
  • Toggle Logic: Switches between 'g10' and 'g100' themes.
  • Validation: Ensures only valid Carbon themes are applied.
  • DOM Integration: Updates document.documentElement.dataset.carbonTheme for global styling.

🛠️ ThemeProvider

<ThemeProvider>
  <App />
</ThemeProvider>

Wraps the app with Carbon’s <Theme> component and provides theme context to all children.

🧠 Custom Hook

const { theme, setTheme, toggleTheme } = useTheme();

Ensures safe access to the theme context and throws an error if used outside the provider.

Waste Plus Wiki

Home

Architecture

Codes

Decisions

Knowledge Base

Development

Changes

Clone this wiki locally