diff --git a/gatsby-ssr.js b/gatsby-ssr.js
index b17b8fc..0a97870 100644
--- a/gatsby-ssr.js
+++ b/gatsby-ssr.js
@@ -1,7 +1,29 @@
-/**
- * Implement Gatsby's SSR (Server Side Rendering) APIs in this file.
- *
- * See: https://www.gatsbyjs.org/docs/ssr-apis/
- */
+import React from "react"
-// You can delete this file if you're not using it
+const ThemeScript = () => {
+ const themeScript = `
+(function() {
+ function getInitialTheme() {
+ const userSetTheme = window.localStorage.getItem("theme")
+ const prefersLightTheme = window.matchMedia(
+ "(prefers-color-scheme: light)"
+ )
+
+ if (userSetTheme && userSetTheme !== '"unset"') return userSetTheme
+ else if (prefersLightTheme.matches === true) return "light"
+ else return "dark"
+ }
+
+ document.documentElement.style.setProperty(
+ "--initial-theme",
+ getInitialTheme()
+ )
+})()
+ `
+
+ return
+}
+
+export const onRenderBody = ({ setPreBodyComponents }) => {
+ setPreBodyComponents()
+}
diff --git a/src/ThemeProvider.tsx b/src/ThemeProvider.tsx
index fab7627..407b70c 100644
--- a/src/ThemeProvider.tsx
+++ b/src/ThemeProvider.tsx
@@ -26,7 +26,9 @@ const ThemeProvider: FC = ({ children }) => {
// App's current theme
const [theme, setTheme] = useState(
- localTheme === "unset" ? "dark" : localTheme
+ document.documentElement.style.getPropertyValue(
+ "--initial-theme"
+ ) as ThemeType
)
const themeObject = useMemo(
@@ -40,8 +42,6 @@ const ThemeProvider: FC = ({ children }) => {
"(prefers-color-scheme: light)"
)
- setTheme(prefersLightTheme.matches ? "light" : "dark")
-
prefersLightTheme.onchange = ({ matches }) =>
setTheme(matches ? "light" : "dark")