API reference

useTheme

stable
function useTheme(): Theme | undefined
Updated 3 days agoEdit on GitHubWeb & native

Description

Returns the active theme — the full Theme object resolved by the closest <ThemeProvider> (or nested <Theme> boundary). Returns undefined when no provider is in scope.

Most styled code does not need this hook. Token references on style props (bg="$colors.surface.base") compile to var(--…) strings on the web; the cascade does the work without a context read.

When to reach for it

  • You need the literal token value (e.g. drawing on a canvas, computing a derived colour).
  • You are doing platform-specific work that the style-prop pipeline does not cover.
  • You are integrating a third-party component that takes raw values rather than CSS variables.

Resolution semantics

Inside a <Theme name="red"> nested under <ThemeProvider active="dark">, the hook returns dark_red if that combination theme is registered, falling back to the inner-most name (red), and ultimately to the root active (dark) if no nested theme matches.

The returned object is the Theme literal the caller passed to <ThemeProvider themes={...}>createTheme is a pass-through factory at runtime.

Example

example.tsx
import { useTheme, Box } from 'usemotif';
 
function Sparkline({ data }: { data: number[] }) {
const theme = useTheme();
const stroke = (theme?.tokens.colors as any)?.action?.primary?.bg ?? '#2563EB';
return (
  <Box as="svg" viewBox="0 0 100 30" w="100%" h={30}>
    <path d={pointsToPath(data)} stroke={stroke} fill="none" strokeWidth={1.5} />
  </Box>
);
}

ThemeContext

For lower-level access — e.g. wiring a custom provider that needs to peek inside the React context directly — ThemeContext is exported.

ThemeContext

stable
const ThemeContext: React.Context<ThemeContextValue | undefined>
example.tsx
interface ThemeContextValue {
readonly themes: readonly Theme[];
readonly active: string;
readonly chain: readonly string[];
}

Application code rarely needs ThemeContext directly. Reach for it when authoring a custom provider or test harness; otherwise prefer the hook surface.