From dc0deb4ead7c94a11f8e466e7f37b3223b85b5bf Mon Sep 17 00:00:00 2001 From: Ou Date: Mon, 14 Oct 2024 17:19:28 +0800 Subject: [PATCH] fix: flash in loading --- src/hooks/useDark.ts | 4 +++- src/routes/__root.tsx | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/hooks/useDark.ts b/src/hooks/useDark.ts index 4e515a3..df45ab3 100644 --- a/src/hooks/useDark.ts +++ b/src/hooks/useDark.ts @@ -4,7 +4,9 @@ import { useLocalStorage, useMedia } from "react-use" export declare type ColorScheme = "dark" | "light" | "auto" export function useDark(key = "color-scheme", defaultColorScheme: ColorScheme = "auto") { - const [colorScheme, setColorScheme] = useLocalStorage(key, defaultColorScheme) + const [colorScheme, setColorScheme] = useLocalStorage(key, defaultColorScheme, { + raw: true, + }) const prefersDarkMode = useMedia("(prefers-color-scheme: dark)") const isDark = useMemo(() => colorScheme === "auto" ? prefersDarkMode : colorScheme === "dark", [colorScheme, prefersDarkMode]) diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 96f3812..a998fe3 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -16,6 +16,12 @@ export const Route = createRootRouteWithContext<{ component: RootComponent, notFoundComponent: NotFoundComponent, beforeLoad: () => { + const theme = localStorage.getItem("color-scheme") || "auto" + const isDark = window.matchMedia("(prefers-color-scheme: dark)").matches + if (!theme ? isDark : theme === "dark") { + document.documentElement.classList.add("dark") + } + const query = new URLSearchParams(window.location.search) if (query.has("login")) { [...query.entries()].forEach(key => localStorage.setItem(key[0], key[1]))