Skip to content

Commit

Permalink
🐛 fix: fix rerender with ThemeSwitcher
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Mar 24, 2024
1 parent eb426b3 commit 8669b88
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 19 deletions.
2 changes: 2 additions & 0 deletions src/factories/createThemeProvider/AntdProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,6 @@ const AntdProvider: FC<AntdProviderProps> = memo(
},
);

AntdProvider.displayName = 'AntdProvider';

export default AntdProvider;
31 changes: 13 additions & 18 deletions src/factories/createThemeProvider/ThemeSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FC, memo, ReactNode, useEffect, useLayoutEffect, useState } from 'react';
import { FC, memo, ReactNode, useLayoutEffect, useState } from 'react';
import useMergeValue from 'use-merge-value';

import { ThemeModeContext } from '@/context';
Expand Down Expand Up @@ -120,16 +120,6 @@ const ThemeSwitcher: FC<ThemeSwitcherProps> = memo(
matchBrowserPrefers('dark')?.matches ? 'dark' : 'light',
);

const [startObserver, setStartObserver] = useState(false);

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

return (
<ThemeModeContext.Provider
value={{
Expand All @@ -141,17 +131,22 @@ const ThemeSwitcher: FC<ThemeSwitcherProps> = memo(
browserPrefers,
}}
>
{startObserver && (
<ThemeObserver
themeMode={themeMode}
setAppearance={setAppearance}
setBrowserPrefers={setBrowserPrefers}
/>
)}
{
// Wait until after client-side hydration to show
typeof window !== 'undefined' && (
<ThemeObserver
themeMode={themeMode}
setAppearance={setAppearance}
setBrowserPrefers={setBrowserPrefers}
/>
)
}
{children}
</ThemeModeContext.Provider>
);
},
);

ThemeSwitcher.displayName = 'ThemeSwitcher';

export default ThemeSwitcher;
4 changes: 3 additions & 1 deletion src/functions/createInstance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext } from 'react';
import { createContext, FC } from 'react';

import { CacheManager, createCSS, createEmotion, serializeCSS } from '@/core';

Expand Down Expand Up @@ -109,6 +109,8 @@ export const createInstance = <T = any>(options: CreateOptions<T>) => {
useTheme,
});

(ThemeProvider as FC).displayName = 'AntdStyleThemeProvider';

// ******** 上面这些都和主题相关,如果做了任何改动,都需要排查一遍 ************ //
const { cx } = createCSS(emotion.cache, { hashPriority: internalOptions.hashPriority });
const { injectGlobal, keyframes } = emotion;
Expand Down

0 comments on commit 8669b88

Please sign in to comment.