diff --git a/src/app/layout.js b/src/app/layout.js
index a2c5431..bb9c0cb 100644
--- a/src/app/layout.js
+++ b/src/app/layout.js
@@ -4,11 +4,33 @@ import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { ThemeToggle } from '@/components/ThemeToggle';
import { ThemeProvider } from '@/components/ThemeContext';
+
export { metadata };
export default function RootLayout({ children }) {
+ const setInitialTheme = `
+ (function() {
+ try {
+ const savedTheme = localStorage.getItem('theme');
+ const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ const theme = savedTheme || (prefersDark ? 'dark' : 'light');
+ if (theme === 'dark') {
+ document.documentElement.classList.add('dark');
+ } else {
+ document.documentElement.classList.remove('dark');
+ }
+ } catch (e) {
+ console.warn('Theme init failed:', e);
+ }
+ })();
+ `;
+
return (
+
+ {/* This runs before the React app mounts, preventing flicker */}
+
+
} />
diff --git a/src/components/ThemeContext.jsx b/src/components/ThemeContext.jsx
index 4656f84..7577ace 100644
--- a/src/components/ThemeContext.jsx
+++ b/src/components/ThemeContext.jsx
@@ -5,19 +5,11 @@ import { createContext, useContext, useState, useEffect } from 'react';
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
- const [theme, setTheme] = useState(null); // Start with `null` to indicate the theme is loading
-
- useEffect(() => {
- // Check initial theme preference
- const savedTheme = localStorage.getItem('theme');
- const prefersDark = window.matchMedia(
- '(prefers-color-scheme: dark)'
- ).matches;
-
- const initialTheme = savedTheme || (prefersDark ? 'dark' : 'light');
- setTheme(initialTheme);
- document.documentElement.classList.toggle('dark', initialTheme === 'dark');
- }, []);
+ const [theme, setTheme] = useState(
+ typeof window !== 'undefined'
+ ? (localStorage.getItem('theme') || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'))
+ : 'light'
+ );
const toggleTheme = () => {
const newTheme = theme === 'light' ? 'dark' : 'light';
@@ -26,9 +18,13 @@ export const ThemeProvider = ({ children }) => {
document.documentElement.classList.toggle('dark', newTheme === 'dark');
};
+ useEffect(() => {
+ document.documentElement.classList.toggle('dark', theme === 'dark');
+ }, [theme]);
+
return (
- {theme !== null && children}
+ {children}
);
};
diff --git a/src/components/ThemeToggle.jsx b/src/components/ThemeToggle.jsx
index 1210d01..e95e6c2 100644
--- a/src/components/ThemeToggle.jsx
+++ b/src/components/ThemeToggle.jsx
@@ -18,4 +18,4 @@ export const ThemeToggle = () => {
)}
);
-};
+};
\ No newline at end of file