Skip to content

Instantly share code, notes, and snippets.

@diego3g
Last active February 25, 2024 07:02
Show Gist options
  • Save diego3g/781327b4a478e01d886af3808af60d18 to your computer and use it in GitHub Desktop.
Save diego3g/781327b4a478e01d886af3808af60d18 to your computer and use it in GitHub Desktop.
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>
)
}
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