From 9647dc1f460f502b4bc6ec91aa4d924e3f262ec1 Mon Sep 17 00:00:00 2001 From: John Doe Date: Sat, 9 Sep 2023 16:54:15 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=A0=EF=B8=8F=20Implement=20theme=20mod?= =?UTF-8?q?e=20functionality?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added code for handling theme mode with dark and light options. This code uses local storage to remember the user's theme preference. Includes functions for toggling between dark and light modes. Ready to enhance the user experience with themes! Let's bring some visual flair to our app! 🌙🌞 --- src/utils/useThemeMode.ts | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/utils/useThemeMode.ts diff --git a/src/utils/useThemeMode.ts b/src/utils/useThemeMode.ts new file mode 100644 index 0000000..11c7911 --- /dev/null +++ b/src/utils/useThemeMode.ts @@ -0,0 +1,54 @@ +import { useEffect } from "react"; +import { createGlobalState } from "react-hooks-global-state"; + +const initialState = { isDarkmode: false }; +const { useGlobalState } = createGlobalState(initialState); + +export const useThemeMode = () => { + const [isDarkMode, setIsDarkMode] = useGlobalState("isDarkmode"); + + useEffect(() => { + // Enbale this if you want use the dark-mode for default mode. + // if (!localStorage.theme) { + // localStorage.theme = "dark"; + // } + // + if (localStorage.theme === "dark") { + toDark(); + } else { + toLight(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const toDark = () => { + setIsDarkMode(true); + const root = document.querySelector("html"); + if (!root) return; + !root.classList.contains("dark") && root.classList.add("dark"); + localStorage.theme = "dark"; + }; + + const toLight = () => { + setIsDarkMode(false); + const root = document.querySelector("html"); + if (!root) return; + root.classList.remove("dark"); + localStorage.theme = "light"; + }; + + function _toogleDarkMode() { + if (localStorage.theme === "light") { + toDark(); + } else { + toLight(); + } + } + + return { + isDarkMode, + toDark, + toLight, + _toogleDarkMode, + }; +};