Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: improve DarkModeSwitch theme handling #6033

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/theme/BackToTopButton/DarkModeSwitch.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React , {useEffect} from 'react'
import React, { useEffect } from 'react'
import clsx from 'clsx'
import {
IconShapeSunLong,
Expand All @@ -7,12 +7,16 @@ import {
import { useColorMode } from '@docusaurus/theme-common'

export default function DarkModeSwitch() {

const { colorMode, setColorMode } = useColorMode(null)
useEffect(() => {
setColorMode(localStorage.getItem('theme'))
}, [])
useEffect(() => {
const savedTheme = localStorage.getItem('theme')
if (savedTheme !== colorMode) {
setColorMode(savedTheme)
}
}, [colorMode, setColorMode])

Comment on lines +11 to +16
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current dependency array [colorMode, setColorMode] will trigger the effect whenever colorMode changes, which can create an infinite loop since the effect itself updates colorMode. Since this effect only needs to run once to initialize the theme from localStorage, the dependency array should be []. This will ensure the effect runs only when the component mounts.

Spotted by Graphite Reviewer

Is this helpful? React 👍 or 👎 to let us know.

const isDark = colorMode === 'dark'

return (
<button
className={clsx(
Expand Down
Loading