tanstack-router-theme-provider
v0.1.5
Published
Dark mode provider for TanStack Router and TanStack Start apps
Downloads
47
Readme
tanstack-router-theme-provider 
SSR-friendly <ThemeProvider /> and useTheme hook for dark mode support in TanStack Router and TanStack Start apps.
Features
- Perfect dark mode support in 2 lines of code
- Supports
light,dark, andsystemthemes - Compatible with shadcn-ui out-of-the-box
- Persists the selected theme in
localStorage - Applies
darkorlightclass to the root<html> - Sets the browser
color-schemeautomatically - Syncs theme changes across browser tabs instantaneously
- Includes startup script to prevent avoid theme flicker on first paint (FOUC)
Installation
npm install tanstack-router-theme-providerPeer dependencies:
react>=18.0.0react-dom>=18.0.0@tanstack/react-router>=1.0.0
Usage
Wrap your root route (src/routes/__root.tsx) with <ThemeProvider> and add supressHydrationWarning on the <html> tag:
// add this after existing imports..
import { ThemeProvider } from 'tanstack-router-theme-provider'
function RootComponent() {
return (
<html lang="en" suppressHydrationWarning>
<head>
<HeadContent />
</head>
<body>
<ThemeProvider>
<Outlet />
<Scripts />
</ThemeProvider>
</body>
</html>
)
}
export const Route = createRootRoute({
components: RootComponent,
// other code..
})
Use useTheme anywhere below the provider.
import { useTheme } from 'tanstack-router-theme-provider'
export function ThemeToggle() {
const { theme, resolvedTheme, setTheme, mounted } = useTheme()
if (!mounted) return null
return (
<button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
Current theme: {theme} ({resolvedTheme})
</button>
)
}How it works:
themecan have the valuelight,dark, orsystem(i.e. OS setting)setThemestores the provided theme inlocalStorageon the clientresolvedThemeisundefinedon the server (i.e. during SSR) sincelocalStorageis not accessible thereresolvedThemeislightordarkon the client based on theprefers-color-scheme: darkmedia querymountedisfalseon the server (i.e. during SSR) andtrueon the client
Reference
You can customize the ThemeProvider provider using the following props:
| Name | Type | Description | Default |
| --- | --- | --- | --- |
| children | React.ReactNode | The app content rendered inside the provider. | Required |
| defaultTheme | 'dark' \| 'light' \| 'system' | The initial theme to use when there is no saved value in storage. | 'system' |
| storageKey | string | The localStorage key used to persist the selected theme. | 'tanstack-ui-theme' |
Development
- Install dependencies:
npm install- Build the library:
npm run build