Skip to content

Commit

Permalink
🐛 fix: fix suspense hydration with ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Jun 3, 2023
1 parent 24888e9 commit 9f27b16
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/factories/createThemeProvider/ThemeSwitcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import useMergeValue from 'use-merge-value';
import { ThemeModeContext } from '@/context';
import { BrowserPrefers, ThemeAppearance, ThemeMode, UseTheme } from '@/types';
import { matchBrowserPrefers } from '@/utils/matchBrowserPrefers';
import { safeStartTransition } from '@/utils/safeStartTransition';

let darkThemeMatch: MediaQueryList;

Expand Down Expand Up @@ -32,7 +33,9 @@ const ThemeObserver: FC<{
useLayoutEffect(() => {
// 如果不是自动,就明确设定亮暗色
if (themeMode !== 'auto') {
setAppearance(themeMode);
safeStartTransition(() => {
setAppearance(themeMode);
});
return;
}
// 如果是自动的话,则去做一次匹配,并开始监听
Expand All @@ -48,7 +51,7 @@ const ThemeObserver: FC<{
};
}, [themeMode]);

useEffect(() => {
useLayoutEffect(() => {
if (!darkThemeMatch) {
darkThemeMatch = matchBrowserPrefers('dark');
}
Expand Down Expand Up @@ -117,7 +120,10 @@ const ThemeSwitcher: FC<ThemeSwitcherProps> = memo(

// Wait until after client-side hydration to show
useEffect(() => {
setStartObserver(true);
// 兼容 React18 的 Suspense 问题
safeStartTransition(() => {
setStartObserver(true);
});
}, []);

return (
Expand Down
9 changes: 9 additions & 0 deletions src/utils/safeStartTransition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { startTransition, TransitionFunction } from 'react';

export const safeStartTransition = (func: TransitionFunction) => {
if (typeof startTransition === 'function') {
startTransition(func);
} else {
func();
}
};

0 comments on commit 9f27b16

Please sign in to comment.