@@ -18,17 +18,9 @@ const ThemeContext = createContext({
1818
1919export function ThemeProvider ( { children, defaultTheme = "system" } ) {
2020 const [ theme , setTheme ] = useState ( defaultTheme ) ;
21-
22- // Detect system preference synchronously during initialization
23- const getInitialSystemTheme = ( ) => {
24- if ( defaultTheme !== "system" ) return defaultTheme ;
25- if ( typeof window === "undefined" ) return "light" ;
26- return window . matchMedia ( "(prefers-color-scheme: dark)" ) . matches
27- ? "dark"
28- : "light" ;
29- } ;
30-
31- const [ systemTheme , setSystemTheme ] = useState ( getInitialSystemTheme ) ;
21+ const [ systemTheme , setSystemTheme ] = useState (
22+ defaultTheme !== "system" ? defaultTheme : "light" ,
23+ ) ;
3224 const [ isInitialized , setIsInitialized ] = useState ( false ) ;
3325
3426 const firstRender = useRef ( true ) ;
@@ -45,6 +37,7 @@ export function ThemeProvider({ children, defaultTheme = "system" }) {
4537 if ( lastCompiledTheme !== defaultColorMode ) {
4638 // on app startup, make sure the application color mode is persisted correctly.
4739 localStorage . setItem ( "last_compiled_theme" , defaultColorMode ) ;
40+ setIsInitialized ( true ) ;
4841 return ;
4942 }
5043 }
@@ -78,19 +71,21 @@ export function ThemeProvider({ children, defaultTheme = "system" }) {
7871 } ;
7972 } ) ;
8073
81- // Save theme to localStorage whenever it changes (but not on initial mount)
74+ // Save theme to localStorage whenever it changes
75+ // Skip saving only if theme key already exists and we haven't initialized yet
8276 useEffect ( ( ) => {
83- if ( isInitialized ) {
84- localStorage . setItem ( "theme" , theme ) ;
85- }
86- } , [ theme , isInitialized ] ) ;
77+ const existingTheme = localStorage . getItem ( "theme" ) ;
78+ if ( ! isInitialized && existingTheme !== null ) return ;
79+ localStorage . setItem ( "theme" , theme ) ;
80+ } , [ theme ] ) ;
8781
8882 useEffect ( ( ) => {
83+ if ( ! isInitialized ) return ;
8984 const root = window . document . documentElement ;
9085 root . classList . remove ( "light" , "dark" ) ;
9186 root . classList . add ( resolvedTheme ) ;
9287 root . style . colorScheme = resolvedTheme ;
93- } , [ resolvedTheme ] ) ;
88+ } , [ resolvedTheme , isInitialized ] ) ;
9489
9590 return createElement (
9691 ThemeContext . Provider ,
0 commit comments