Skip to content

Commit 24d01bb

Browse files
authored
fix(theme): fix useColorMode() visual glitches due to provider unmounts/remounts (#11405)
1 parent 1c484e1 commit 24d01bb

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

packages/docusaurus-theme-common/src/contexts/colorMode.tsx

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import React, {
1313
useMemo,
1414
type ReactNode,
1515
} from 'react';
16+
import useIsBrowser from '@docusaurus/useIsBrowser';
1617
import {ReactContextError} from '../utils/reactUtils';
1718
import {createStorageSlot} from '../utils/storageUtils';
1819
import {useThemeConfig} from '../utils/useThemeConfig';
@@ -124,10 +125,17 @@ function useColorModeState() {
124125
const {
125126
colorMode: {defaultMode},
126127
} = useThemeConfig();
128+
const isBrowser = useIsBrowser();
127129

128-
const [colorMode, setColorModeState] = useState<ColorMode>(defaultMode);
129-
const [colorModeChoice, setColorModeChoiceState] =
130-
useState<ColorModeChoice>(null);
130+
// Since the provider may unmount/remount on client navigation, we need to
131+
// reinitialize the state with the correct values to avoid visual glitches.
132+
// See also https://github.com/facebook/docusaurus/issues/11399#issuecomment-3279181314
133+
const [colorMode, setColorModeState] = useState<ColorMode>(
134+
isBrowser ? ColorModeAttribute.get() : defaultMode,
135+
);
136+
const [colorModeChoice, setColorModeChoiceState] = useState<ColorModeChoice>(
137+
isBrowser ? ColorModeChoiceAttribute.get() : null,
138+
);
131139

132140
useEffect(() => {
133141
setColorModeState(ColorModeAttribute.get());

0 commit comments

Comments
 (0)