Skip to content

Commit 3002619

Browse files
committed
feat: useTheme 支持 ssr
1 parent c7bb04c commit 3002619

File tree

2 files changed

+11714
-13023
lines changed

2 files changed

+11714
-13023
lines changed

packages/hooks/src/useTheme/index.ts

+14-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { useEffect, useState } from 'react';
22
import useMemoizedFn from '../useMemoizedFn';
3+
import isBrowser from '../utils/isBrowser';
34

45
export enum ThemeMode {
56
LIGHT = 'light',
@@ -11,12 +12,18 @@ export type ThemeModeType = `${ThemeMode}`;
1112

1213
export type ThemeType = 'light' | 'dark';
1314

14-
const matchMedia = window.matchMedia('(prefers-color-scheme: dark)');
1515

1616
function useCurrentTheme() {
17+
const matchMedia = isBrowser
18+
? window.matchMedia('(prefers-color-scheme: dark)')
19+
: undefined;
20+
1721
const [theme, setTheme] = useState<ThemeType>(() => {
18-
const init = matchMedia.matches ? ThemeMode.DARK : ThemeMode.LIGHT;
19-
return init;
22+
if (isBrowser) {
23+
return matchMedia?.matches ? ThemeMode.DARK : ThemeMode.LIGHT;
24+
} else {
25+
return ThemeMode.LIGHT;
26+
}
2027
});
2128

2229
useEffect(() => {
@@ -28,10 +35,10 @@ function useCurrentTheme() {
2835
}
2936
};
3037

31-
matchMedia.addEventListener('change', onThemeChange);
38+
matchMedia?.addEventListener('change', onThemeChange);
3239

3340
return () => {
34-
matchMedia.removeEventListener('change', onThemeChange);
41+
matchMedia?.removeEventListener('change', onThemeChange);
3542
};
3643
}, []);
3744

@@ -47,7 +54,8 @@ export default function useTheme(options: Options = {}) {
4754

4855
const [themeMode, setThemeMode] = useState<ThemeModeType>(() => {
4956
const preferredThemeMode =
50-
localStorageKey?.length && (localStorage.getItem(localStorageKey) as ThemeModeType | null);
57+
localStorageKey?.length &&
58+
(localStorage.getItem(localStorageKey) as ThemeModeType | null);
5159

5260
return preferredThemeMode ? preferredThemeMode : ThemeMode.SYSTEM;
5361
});

0 commit comments

Comments
 (0)