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

fix: fix ssr bug #2691

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
38 changes: 22 additions & 16 deletions packages/hooks/src/useTheme/index.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,47 @@
import { useEffect, useState } from 'react';
import useMemoizedFn from '../useMemoizedFn';
import { useEffect, useState } from "react";
import useMemoizedFn from "../useMemoizedFn";
import isBrowser from "../utils/isBrowser";

export enum ThemeMode {
LIGHT = 'light',
DARK = 'dark',
SYSTEM = 'system',
LIGHT = "light",
DARK = "dark",
SYSTEM = "system",
}

export type ThemeModeType = `${ThemeMode}`;

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

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

function useCurrentTheme() {
const 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(() => {
const onThemeChange: MediaQueryList['onchange'] = (event) => {
const onThemeChange: MediaQueryList["onchange"] = (event) => {
if (event.matches) {
setTheme(ThemeMode.DARK);
} else {
setTheme(ThemeMode.LIGHT);
}
};

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

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

return theme;
}
};

type Options = {
localStorageKey?: string;
Expand All @@ -47,7 +52,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