Frameworks
TanStack Start
Setup guide for TanStack Start
Installation
npm install better-themesSetup
Update your root route
In your root route file (typically routes/__root.tsx), wrap your app with ThemeProvider:
import { createRootRoute } from "@tanstack/react-router";
import { ThemeProvider } from "better-themes";
import { HeadContent, Scripts } from "@tanstack/react-router";
function RootDocument({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<HeadContent />
</head>
<body>
<ThemeProvider attribute="class" disableTransitionOnChange>
{children}
</ThemeProvider>
<Scripts />
</body>
</html>
);
}
export const Route = createRootRoute({
component: RootDocument,
});Create a theme switcher component
import { useTheme } from "better-themes";
import { useHydrated } from "@tanstack/react-router";
export function ThemeSwitcher() {
const hydrated = useHydrated();
const { theme, setTheme } = useTheme();
return (
<button
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
disabled={!hydrated}
>
{hydrated ? `Current: ${theme}` : "Loading..."}
</button>
);
}Complete Example
import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router";
import { ThemeProvider } from "better-themes";
import { ThemeSwitcher } from "@/components/theme-switcher";
function RootDocument({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<HeadContent />
</head>
<body>
<ThemeProvider attribute="class" disableTransitionOnChange>
<ThemeSwitcher />
{children}
</ThemeProvider>
<Scripts />
</body>
</html>
);
}
export const Route = createRootRoute({
component: RootDocument,
});Notes
- Use the default export for TanStack Start
- Add
suppressHydrationWarningto the<html>tag
Example
View a complete example implementation: TanStack Start Example
Try the live demo: Live Demo