From 4925372ad880e6ade37ce0c1ee921cb41971cf03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A0=97=E5=98=89=E7=94=B7?= <574980606@qq.com> Date: Thu, 5 Dec 2024 14:31:18 +0800 Subject: [PATCH] fix: fix ssr bug --- packages/hooks/src/useTheme/index.ts | 38 ++++++++++++++++------------ 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/packages/hooks/src/useTheme/index.ts b/packages/hooks/src/useTheme/index.ts index 9eb3899dcc..58b98de767 100644 --- a/packages/hooks/src/useTheme/index.ts +++ b/packages/hooks/src/useTheme/index.ts @@ -1,26 +1,31 @@ -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(() => { - 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 { @@ -28,15 +33,15 @@ function useCurrentTheme() { } }; - matchMedia.addEventListener('change', onThemeChange); + matchMedia?.addEventListener("change", onThemeChange); return () => { - matchMedia.removeEventListener('change', onThemeChange); + matchMedia?.removeEventListener("change", onThemeChange); }; }, []); return theme; -} +}; type Options = { localStorageKey?: string; @@ -47,7 +52,8 @@ export default function useTheme(options: Options = {}) { const [themeMode, setThemeMode] = useState(() => { const preferredThemeMode = - localStorageKey?.length && (localStorage.getItem(localStorageKey) as ThemeModeType | null); + localStorageKey?.length && + (localStorage.getItem(localStorageKey) as ThemeModeType | null); return preferredThemeMode ? preferredThemeMode : ThemeMode.SYSTEM; });