File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11'use client'
22
3- import { useState } from 'react'
3+ import { useEffect , useState } from 'react'
44
55type Theme = 'light' | 'dark'
66
@@ -11,19 +11,21 @@ interface Props {
1111 darkLabel : string
1212}
1313
14- function detectTheme ( ) : Theme {
15- if ( typeof window === 'undefined' ) return 'light'
16- const saved = window . localStorage . getItem ( THEME_KEY )
17- if ( saved === 'light' || saved === 'dark' ) return saved
18- return window . matchMedia ( '(prefers-color-scheme: dark)' ) . matches ? 'dark' : 'light'
19- }
20-
2114function applyTheme ( theme : Theme ) {
2215 document . documentElement . classList . toggle ( 'dark' , theme === 'dark' )
2316}
2417
2518export default function ThemeToggle ( { lightLabel, darkLabel } : Props ) {
26- const [ theme , setTheme ] = useState < Theme > ( ( ) => detectTheme ( ) )
19+ const [ theme , setTheme ] = useState < Theme | null > ( null )
20+
21+ useEffect ( ( ) => {
22+ const timer = window . setTimeout ( ( ) => {
23+ const fromDom = document . documentElement . classList . contains ( 'dark' ) ? 'dark' : 'light'
24+ setTheme ( fromDom )
25+ } , 0 )
26+
27+ return ( ) => window . clearTimeout ( timer )
28+ } , [ ] )
2729
2830 function updateTheme ( nextTheme : Theme ) {
2931 setTheme ( nextTheme )
You can’t perform that action at this time.
0 commit comments