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, + }; +};