Skip to content

Instantly share code, notes, and snippets.

@MaymoonaAlBoloshi
Created June 19, 2022 08:36
Show Gist options
  • Save MaymoonaAlBoloshi/d1561e6038693acddad3796731693192 to your computer and use it in GitHub Desktop.
Save MaymoonaAlBoloshi/d1561e6038693acddad3796731693192 to your computer and use it in GitHub Desktop.
// 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();
@MaymoonaAlBoloshi
Copy link
Author

MaymoonaAlBoloshi commented Jun 19, 2022

usePresist


themeType:

export enum themeType {
	light = 'light',
	dark = 'dark',
}

The parent component I'm using in the main.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';
import { ThemeProvider, useTheme } from './context';

ReactDOM.createRoot(document.getElementById('root')!).render(
	<React.StrictMode>
	    <ThemeProvider>
		    <App />
	    </ThemeProvider>
	</React.StrictMode>
);

use the theme context, I'm using mine in app.tsx

import { useTheme } from './context';
import './App.css';

function App() {
	const { theme, themeLoaded } = useTheme();
	console.log(theme);
	console.log(themeLoaded);
	return (
            <>
                {themeLoaded && (
                      <div className='App' data-theme={theme}>
                            app goes here ...
                        </Routes>
                      </div>
                )}
            </>
	);
}

export default App;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment