Dark/light/system theme provider for React with localStorage persistence and system preference detection
npm install @philiprehberger/react-theme-providerDark/light/system theme provider for React with localStorage persistence and system preference detection
npm install @philiprehberger/react-theme-provider
Wrap your app with the provider:
import { ThemeProvider } from '@philiprehberger/react-theme-provider';
function App() {
return (
<ThemeProvider defaultTheme="system" storageKey="theme">
<YourApp />
</ThemeProvider>
);
}
Access theme state from any component:
import { useTheme } from '@philiprehberger/react-theme-provider';
function MyComponent() {
const { theme, setTheme, resolvedTheme } = useTheme();
// theme: 'light' | 'dark' | 'system'
// resolvedTheme: 'light' | 'dark' (actual applied theme)
}
Shorthand when you only need the resolved value:
import { useResolvedTheme } from '@philiprehberger/react-theme-provider';
function Logo() {
const theme = useResolvedTheme(); // 'light' | 'dark'
return <img src={theme === 'dark' ? '/logo-dark.svg' : '/logo-light.svg'} />;
}
<ThemeProvider disableTransitionOnChange>
<YourApp />
</ThemeProvider>
Suppresses CSS transitions for one frame while the new theme class is applied — useful if your app uses long color transitions that would otherwise flicker on switch.
Pre-built toggle component with sun/moon/system icons:
import { ThemeToggle } from '@philiprehberger/react-theme-provider';
<ThemeToggle />
| Export | Type | Description |
|---|---|---|
ThemeProvider | Component | Context provider with localStorage persistence and system preference detection |
useTheme() | Hook | Returns { theme, setTheme, resolvedTheme } for reading/setting theme |
useResolvedTheme() | Hook | Returns just the resolved theme: 'light' | 'dark' |
ThemeToggle | Component | Pre-built three-way toggle (light/dark/system) with sun/moon/system icons |
Theme | Type | 'light' | 'dark' | 'system' |
ResolvedTheme | Type | 'light' | 'dark' (the actual applied theme) |
ThemeContextType | Type | Shape of the theme context value |
ThemeProviderProps | Type | Props for ThemeProvider (children, storageKey?, defaultTheme?, disableTransitionOnChange?) |
ThemeToggleProps | Type | Props for ThemeToggle (className?, activeClassName?, inactiveClassName?) |
light or dark class to document.documentElementlocalStorageprefers-color-scheme changes when set to systemdark: variant out of the boxnpm install
npm run build
npm test
If you find this project useful: