Skip to content

Commit

Permalink
add theme context
Browse files Browse the repository at this point in the history
  • Loading branch information
firehawk89 committed Sep 29, 2023
1 parent 181081f commit a5b2fe4
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions src/store/theme-context.jsx
Original file line number Diff line number Diff line change
@@ -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 (
<ThemeContext.Provider
value={{
isDarkMode,
enableDarkMode: enableDarkModeHandler,
disableDarkMode: disableDarkModeHandler,
}}
>
{children}
</ThemeContext.Provider>
)
}

export default ThemeContext

0 comments on commit a5b2fe4

Please sign in to comment.