Skip to content

Commit 191b0d3

Browse files
committed
Correction du mismatch hydratation dans le fichier themetoggle
1 parent 4f6af6f commit 191b0d3

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

components/ThemeToggle.tsx

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client'
22

3-
import { useState } from 'react'
3+
import { useEffect, useState } from 'react'
44

55
type 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-
2114
function applyTheme(theme: Theme) {
2215
document.documentElement.classList.toggle('dark', theme === 'dark')
2316
}
2417

2518
export 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)

0 commit comments

Comments
 (0)