Dark Mode
A lightweight, dependency-free theme system for React. Add it once to your application and control light or dark mode from anywhere.
How it works
The theme provider keeps track of the active theme and synchronizes it with your document. Once it is added to your layout, any client component inside the provider can control the theme.
Create the provider
Add the theme logic to a reusableThemeProvidercomponent.
Wrap your application
Add the provider once inside yourlayout.tsxfile.
Add this line in your globals.css
@custom-variant dark (&:is(.dark *));Control it anywhere
UsesetTheme()from any component inside the provider.
Create ThemeProvider.tsx
Create the provider that manages the active theme, persists the user's preference, and applies the theme class to the document root.
Keeps track of whether the application is currently using light or dark mode.
Stores the selected theme so the preference can be restored when the user returns.
Automatically adds or removes the dark class when the theme changes.
The provider can fall back to the user's operating-system theme when no preference is stored.
Add it to your layout.tsx
Wrap your application with ThemeProvider once. Every component inside it can then access and control the current theme.
You only need to add the provider once. There is no need to initialize the theme again on individual pages or components.
Add it to your globals.tsx
Add this custom-variant into your globals file
@custom-variant dark (&:is(.dark *));Control the theme from anywhere
Access the theme API from any client component inside the provider. Set a specific theme or build your own toggle UI.
Build your own theme control
The theme API is intentionally small. Use setTheme() to build a switcher that matches your application's design.
Theme API
The provider exposes a small API for reading and changing the active theme.
themesetTheme("dark")setTheme("light")Use dark mode in your components
Once the provider is configured, you can use Tailwind's standard dark: variant normally.
<div
className="
bg-white
text-black
dark:bg-black
dark:text-white
"
>
Hello, world.
</div>The provider does not control your component styles. It simply manages the theme state and document class, allowing your existing dark: styles to respond automatically.
That's all you need.
Create the provider, add it to your layout, and control the theme wherever you need it. No external theme library is required.