Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: useTheme 支持 ssr #2692

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading