A theme provider for React
npm install better-themesA theme provider for React
  
- Zero flash on load - Prevents theme flash during page load (SSR/SSG safe)
- System preference detection - Automatically detects and respects user's system theme preference via prefers-color-scheme
- Cross-tab synchronization - Theme changes sync across browser tabs and windows
- Themed browser UI - Sets color-scheme CSS property for native browser UI elements
- Custom themes - Support for multiple custom themes beyond light/dark
- Flexible styling - Use class or data attributes (works with Tailwind CSS)
- TypeScript - Fully typed with TypeScript
- Framework agnostic - Works with Next.js, Remix, Vite, TanStack Start, Waku, and more
``bash`
npm install better-themesor
pnpm add better-themesor
yarn add better-themesor
bun add better-themes
Wrap your app with ThemeProvider at the root of your application.
For React Server Components, import from better-themes/rsc:
`tsx
import { ThemeProvider } from "better-themes/rsc";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
$3
For client-side applications or other frameworks:
`tsx
import { ThemeProvider } from "better-themes";function App() {
return (
{/ Your app content /}
);
}
`> Important: Add
suppressHydrationWarning to your tag to prevent hydration warnings.Usage
Access the current theme and change it with the
useTheme hook:`tsx
"use client"import { useTheme } from "better-themes";
function ThemeToggle() {
const { theme, setTheme, themes } = useTheme();
return (
Current theme: {theme}
);
}
`Configuration
The
ThemeProvider accepts the following props:-
themes - List of available theme names (default: ["light", "dark"])
- defaultTheme - Default theme when no preference is saved (default: "system" if enableSystem is true, else "light")
- storageKey - localStorage key for storing theme preference (default: "theme")
- forcedTheme - Force a specific theme (overrides user preference)
- enableSystem - Enable system theme detection (default: true)
- enableColorScheme - Set color-scheme CSS property (default: true)
- attribute - HTML attribute to modify (default: "class", can be "class" or "data-*")
- value - Map theme names to attribute values
- disableTransitionOnChange - Disable CSS transitions on switch (default: false)
- nonce - Nonce for CSP headersStyling with Tailwind CSS
Use class-based dark mode in Tailwind:
`tsx
{children}
`Then use dark variants:
`tsx
Hello World
``For complete documentation, examples, and recipes, visit https://better-themes.netlify.app
This project is inspired by and based on next-themes by Paco Coursey and tanstack-theme-kit by augiwan.
MIT