Unexpected Theme Switch to Light Mode After User Login
Description:
After integrating the next-themes library into my Next.js application, I encountered an unexpected behavior related to theme switching. I'll describe the issue below without sharing my app's source code or providing access to the app itself.
Steps to Reproduce:
Navigate to the application in a fresh browser session. Observe that the default theme is correctly set to dark mode. Log in as a user. Observe that the UI unexpectedly switches to light mode, even though the theme is set to dark mode.
Expected Behavior:
The theme of the application should consistently remain in dark mode after the user logs in, as configured in the next-themes library's ThemeProvider.
Actual Behavior:
After the user logs in, the UI switches to light mode, despite the theme being set to dark mode.
Relevant Code:
theme.provider.tsx
"use client";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { FC, ReactNode, useEffect, useState } from "react";
type ProvidersProps = {
children: ReactNode;
};
const ThemeProvider: FC<ProvidersProps> = ({ children }) => {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return <>{children}</>;
}
return (
<NextThemesProvider defaultTheme="dark" attribute="class">
{children}
</NextThemesProvider>
);
};
export default ThemeProvider;
layout.tsx
export default async function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html
suppressHydrationWarning
lang="en"
>
<body className="bg-white dark:bg-black">
<ThemeProvider>
...
</ThemeProvider>
</body>
</html>
);
}
Additional Information:
Application framework: Next.js v13.4.12
Authentication library: NextAuth.js v4.22.5
Theme management library: next-themes v0.2.1
Other relevant libraries and dependencies: tailwindcss v3.3.3
Environment:
Operating System: macOS 13.4.1 Browser: Chrome Version 115.0.5790.170 (Official Build) (arm64)
Source: pacocoursey/next-themes