Skip to content

useTheme

Hook to detect and control the current theme. Supports system preference detection, theme persistence, and provides computed colors for canvas-based components.

import { useTheme, ThemeProvider } from 'asterui'

Wrap your app with ThemeProvider to enable full theme control:

main.tsx
import { ThemeProvider } from 'asterui'
createRoot(document.getElementById('root')!).render(
<ThemeProvider defaultTheme="system">
<App />
</ThemeProvider>
)
App.tsx
function App() {
const { theme, setTheme, resolvedTheme, isDark, colors } = useTheme()
return (
<div>
<p>Selected: {theme}</p>
<p>Applied: {resolvedTheme}</p>
<p>Mode: {isDark ? 'Dark' : 'Light'}</p>
<button onClick={() => setTheme('light')}>Light</button>
<button onClick={() => setTheme('dark')}>Dark</button>
<button onClick={() => setTheme('system')}>System</button>
</div>
)
}

When used without a provider, useTheme provides read-only access to the current theme state:

function ThemeAwareComponent() {
const { isDark, colors } = useTheme()
return (
<div style={{ background: colors.background, color: colors.foreground }}>
Current mode: {isDark ? 'Dark' : 'Light'}
</div>
)
}
function CanvasComponent() {
const { colors } = useTheme()
const canvasRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const ctx = canvasRef.current?.getContext('2d')
if (!ctx) return
ctx.fillStyle = colors.background
ctx.fillRect(0, 0, 100, 100)
ctx.fillStyle = colors.primary
ctx.fillText('Hello', 10, 50)
}, [colors])
return <canvas ref={canvasRef} />
}

See ThemeProvider for provider props and configuration options.

PropertyTypeDescription
themestring | undefinedThe selected theme (e.g., 'system', 'light', 'dark'). Only with ThemeProvider.
resolvedThemestring | undefinedThe actual applied theme after resolving 'system'. Only with ThemeProvider.
isDarkbooleantrue if dark mode is active.
setTheme(theme: string) => void | undefinedFunction to change theme. Only with ThemeProvider.
colorsThemeColorsComputed theme colors as hex values.
systemTheme'light' | 'dark' | undefinedThe system preference. Only with ThemeProvider.
PropertyTypeDescription
backgroundstringBase background color (DaisyUI base-100)
foregroundstringBase text color (DaisyUI base-content)
primarystringPrimary color
primaryContentstringPrimary content color
secondarystringSecondary color
accentstringAccent color
infostringInfo color
successstringSuccess color
warningstringWarning color
errorstringError color
  • System Preference Detection: Automatically detects prefers-color-scheme: dark
  • Persistence: Saves user preference to localStorage (configurable)
  • Cross-Tab Sync: Theme changes sync across browser tabs
  • Any DaisyUI Theme: Works with all 30+ built-in themes
  • Reactive Updates: Automatically updates when theme or system preference changes
  • Canvas Support: Provides hex colors for canvas/WebGL contexts