Hooks
useTheme
A hook that provides theme management with system preference detection and localStorage persistence.
useTheme
The useTheme hook provides theme management functionality with features like system preference detection and localStorage persistence. It allows users to easily switch between light, dark, and system themes in your application.
Current theme: system
Installation
Install the useTheme hook using:
Provider Setup
You need to wrap your application with the ThemeProvider to use the useTheme hook:
File Structure
use-theme.ts
ThemeProvider Props
| Prop | Type | Default |
|---|---|---|
children | React.ReactNode | Required |
defaultTheme | "light" | "dark" | "system" | "system" |
storageKey | string | "theme" |
useTheme Return Value
| Prop | Type | Default |
|---|---|---|
theme | "light" | "dark" | "system" | - |
setTheme | (theme: 'light' | 'dark' | 'system') => void | - |
Examples
Theme Switcher with Buttons
A simple theme switcher with separate buttons for each theme option.
Current theme: system
Theme Toggle
A simple toggle switch between light and dark mode.
Use Cases
- Website Theming: Implement light and dark modes for your website
- User Preferences: Respect user’s system preferences while allowing manual override
- Accessibility: Support users who prefer specific contrast levels
- Reading Modes: Implement reading-friendly themes for content-heavy sites
- Branded Experiences: Create themed experiences for different sections of your app
Accessibility
The useTheme hook enhances accessibility by:
- Supporting system preferences for users who have set their OS to dark or light mode
- Persisting theme choices for returning users
- Allowing users to select their preferred theme for better reading comfort
- Supporting reduced motion preferences when combined with appropriate CSS
Best Practices
- Include the
ThemeProviderat the root of your application - Use CSS variables for theme colors to ensure consistent theming
- Add the
suppressHydrationWarningattribute to thehtmlelement to avoid hydration warnings - Consider offering a high contrast theme option for users with visual impairments
- Use semantic color names in your CSS variables (e.g.,
--background,--foreground) rather than light/