-
-
Save lucasgomesoficial/c769a546979eb96904d21c7ecae037ae to your computer and use it in GitHub Desktop.
This file contains hidden or 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 hidden or 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