Skip to content

Instantly share code, notes, and snippets.

@nwebpro
Created November 15, 2023 08:33
Show Gist options
  • Save nwebpro/ab5c60ab136091b0942478756e82d334 to your computer and use it in GitHub Desktop.
Save nwebpro/ab5c60ab136091b0942478756e82d334 to your computer and use it in GitHub Desktop.
/* eslint-disable react/prop-types */
import { createContext, useEffect, useState } from "react";
export const ThemeContext = createContext()
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light')
useEffect(() => {
if (localStorage.getItem('theme') === null) {
localStorage.setItem('theme', 'light');
}
}, []);
useEffect(() => {
const html = document.querySelector('html');
if (localStorage.getItem('theme') === 'dark') {
html.classList.add('dark');
setTheme('dark');
} else {
html.classList.remove('dark');
setTheme('light');
}
}, [theme]);
const handleThemeSwitch = () => {
if (localStorage.getItem('theme') === 'light') {
setTheme('dark');
localStorage.setItem('theme', 'dark');
} else {
setTheme('light');
localStorage.setItem('theme', 'light');
}
};
const themeInfo = {
theme,
setTheme,
handleThemeSwitch
}
return (
<ThemeContext.Provider value={ themeInfo }>
{children}
</ThemeContext.Provider>
)
}
export default ThemeProvider
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment