Skip to content

Commit

Permalink
feat: useTheme 支持 ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
crazylxr committed Dec 5, 2024
1 parent c7bb04c commit 3002619
Show file tree
Hide file tree
Showing 2 changed files with 11,714 additions and 13,023 deletions.
20 changes: 14 additions & 6 deletions packages/hooks/src/useTheme/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import isBrowser from '../utils/isBrowser';

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

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

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

function useCurrentTheme() {
const matchMedia = isBrowser
? window.matchMedia('(prefers-color-scheme: dark)')
: undefined;

const [theme, setTheme] = useState<ThemeType>(() => {
const init = matchMedia.matches ? ThemeMode.DARK : ThemeMode.LIGHT;
return init;
if (isBrowser) {
return matchMedia?.matches ? ThemeMode.DARK : ThemeMode.LIGHT;
} else {
return ThemeMode.LIGHT;
}
});

useEffect(() => {
Expand All @@ -28,10 +35,10 @@ function useCurrentTheme() {
}
};

matchMedia.addEventListener('change', onThemeChange);
matchMedia?.addEventListener('change', onThemeChange);

return () => {
matchMedia.removeEventListener('change', onThemeChange);
matchMedia?.removeEventListener('change', onThemeChange);
};
}, []);

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

const [themeMode, setThemeMode] = useState<ThemeModeType>(() => {
const preferredThemeMode =
localStorageKey?.length && (localStorage.getItem(localStorageKey) as ThemeModeType | null);
localStorageKey?.length &&
(localStorage.getItem(localStorageKey) as ThemeModeType | null);

return preferredThemeMode ? preferredThemeMode : ThemeMode.SYSTEM;
});
Expand Down
Loading

0 comments on commit 3002619

Please sign in to comment.