Last active
February 25, 2024 07:02
-
-
Save diego3g/781327b4a478e01d886af3808af60d18 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, ReactNode, useEffect, useState } from 'react' | |
type Theme = 'light' | 'dark'; | |
type ThemeContextProviderProps = { | |
children: ReactNode; | |
} | |
type ThemeContextType = { | |
theme: Theme; | |
toggleTheme: () => void; | |
} | |
export const ThemeContext = createContext({} as ThemeContextType); | |
export function ThemeContextProvider(props: ThemeContextProviderProps) { | |
const [currentTheme, setCurrentTheme] = useState<Theme>(() => { | |
const storagedTheme = localStorage.getItem('theme') | |
return (storagedTheme ?? 'light') as Theme; | |
}); | |
useEffect(() => { | |
localStorage.setItem('theme', currentTheme); | |
}, [currentTheme]) | |
function toggleTheme() { | |
setCurrentTheme(currentTheme === 'light' ? 'dark' : 'light'); | |
} | |
return ( | |
<ThemeContext.Provider value={{ theme: currentTheme, toggleTheme }}> | |
{props.children} | |
</ThemeContext.Provider> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useContext } from 'react'; | |
import { ThemeContext } from '../contexts/ThemeContext' | |
export function useTheme() { | |
const value = useContext(ThemeContext) | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment