Created
June 19, 2022 08:36
-
-
Save MaymoonaAlBoloshi/d1561e6038693acddad3796731693192 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
// persisting Context of theme | |
import React from 'react'; | |
import { useState, useEffect, useContext } from 'react'; | |
import { usePersist } from '../hooks'; | |
import { themeType } from '../types'; | |
export interface IThemeProviderProps { | |
theme: themeType; | |
themeLoaded: boolean; | |
setThemeAndPersist: (theme: themeType) => void; | |
} | |
type Props = { | |
children: React.ReactNode; | |
useState?: () => [string, () => void]; | |
}; | |
export const ThemeContext = React.createContext({} as IThemeProviderProps); | |
export const useTheme = () => useContext(ThemeContext); | |
export function ThemeProvider(props: Props) { | |
const initialTheme = themeType.light; | |
const [persistTheme, setPersistTheme] = usePersist('theme', initialTheme); | |
const [theme, setTheme] = useState<themeType>( | |
persistTheme ? persistTheme : initialTheme | |
); | |
const [themeLoaded, setThemeLoaded] = useState(false); | |
const setThemeAndPersist = (theme: themeType) => { | |
setThemeLoaded(false); | |
setTheme(theme); | |
setPersistTheme(theme); | |
}; | |
useEffect(() => { | |
setTheme(persistTheme); | |
setThemeLoaded(true); | |
}, [persistTheme]); | |
return ( | |
<ThemeContext.Provider value={{ theme, themeLoaded, setThemeAndPersist }}> | |
{props.children} | |
</ThemeContext.Provider> | |
); | |
} | |
// HOW TO USE | |
// import and wrap ThemeProvider to the parent component as : <ThemeProvider> <app/> </ThemeProvider> | |
// import useTheme where ever you need to use the data as : const { theme, themeLoaded, setThemeAndPersist } = useTheme(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usePresist
themeType:
The parent component I'm using in the main.tsx
use the theme context, I'm using mine in app.tsx