useTheme
Theme switching Hook
Overview
useTheme provides theme state management and switching functionality.
Import
import { useTheme } from '@linch-tech/desktop-core';Basic Usage
import { useTheme } from '@linch-tech/desktop-core';
function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<select value={theme} onChange={(e) => setTheme(e.target.value as Theme)}>
<option value="light">Light</option>
<option value="dark">Dark</option>
<option value="system">System</option>
</select>
);
}Return Value
interface UseThemeReturn {
theme: Theme; // Current theme setting
setTheme: (theme: Theme) => void; // Set theme
}
type Theme = 'light' | 'dark' | 'system';Theme Values
| Value | Description |
|---|---|
light | Light mode |
dark | Dark mode |
system | Follow system settings |
How It Works
- Theme value is stored in
localStorage(key:vite-ui-theme) - Based on theme value, adds
lightordarkclass to<html>element - If
system, listens for system theme changes and switches automatically
Using CSS Variables
Theme switching is implemented through Tailwind CSS dark mode:
/* Light mode */
:root {
--background: #ffffff;
--foreground: #000000;
}
/* Dark mode */
.dark {
--background: #1a1a1a;
--foreground: #ffffff;
}Built-in Component
You can use the ThemeSwitcher component directly:
import { ThemeSwitcher } from '@linch-tech/desktop-core';
<ThemeSwitcher />Example: Theme Button
import { useTheme } from '@linch-tech/desktop-core';
import { Sun, Moon, Monitor } from 'lucide-react';
function ThemeButton() {
const { theme, setTheme } = useTheme();
const icons = {
light: <Sun className="h-4 w-4" />,
dark: <Moon className="h-4 w-4" />,
system: <Monitor className="h-4 w-4" />,
};
const next: Record<Theme, Theme> = {
light: 'dark',
dark: 'system',
system: 'light',
};
return (
<button onClick={() => setTheme(next[theme])}>
{icons[theme]}
</button>
);
}Persistence
Theme settings are automatically persisted to localStorage, maintained after page refresh.
// Read
localStorage.getItem('vite-ui-theme'); // 'light' | 'dark' | 'system'
// Write (handled automatically by setTheme)
localStorage.setItem('vite-ui-theme', 'dark');