From a5b2fe44782e75ab220774e86dfa73dc64503e9a Mon Sep 17 00:00:00 2001 From: Bochkovskyi Date: Fri, 29 Sep 2023 19:19:40 +0300 Subject: [PATCH] add theme context --- src/store/theme-context.jsx | 49 +++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/store/theme-context.jsx diff --git a/src/store/theme-context.jsx b/src/store/theme-context.jsx new file mode 100644 index 0000000..32cdc3c --- /dev/null +++ b/src/store/theme-context.jsx @@ -0,0 +1,49 @@ +'use client' + +import { createContext, useEffect, useState } from 'react' + +const ThemeContext = createContext({ + isDarkMode: false, + enableDarkMode: () => {}, + disableDarkMode: () => {}, +}) + +const preferredDarkMode = window.matchMedia( + '(prefers-color-scheme: dark)' +).matches + +export const ThemeContextProvider = ({ children }) => { + const [isDarkMode, setDarkMode] = useState(preferredDarkMode) + + useEffect(() => { + const storedThemeInfo = localStorage.getItem('darkMode') + + if (storedThemeInfo === true) { + setDarkMode(true) + } + }, []) + + const enableDarkModeHandler = () => { + localStorage.setItem('darkMode', true) + setDarkMode(true) + } + + const disableDarkModeHandler = () => { + localStorage.removeItem('darkMode') + setDarkMode(false) + } + + return ( + + {children} + + ) +} + +export default ThemeContext