index.js 1023 B

123456789101112131415161718192021222324252627282930313233343536
  1. import { createContext, useCallback, useContext, useState } from 'react';
  2. const ThemeContext = createContext(null);
  3. export const useTheme = () => useContext(ThemeContext);
  4. const SetThemeContext = createContext(null);
  5. export const useSetTheme = () => useContext(SetThemeContext);
  6. export const ThemeProvider = ({ children }) => {
  7. const [theme, _setTheme] = useState(() => {
  8. try {
  9. return localStorage.getItem('theme-mode') || null;
  10. } catch {
  11. return null;
  12. }
  13. });
  14. const setTheme = useCallback((input) => {
  15. _setTheme(input ? 'dark' : 'light');
  16. const body = document.body;
  17. if (!input) {
  18. body.removeAttribute('theme-mode');
  19. localStorage.setItem('theme-mode', 'light');
  20. } else {
  21. body.setAttribute('theme-mode', 'dark');
  22. localStorage.setItem('theme-mode', 'dark');
  23. }
  24. }, []);
  25. return (
  26. <SetThemeContext.Provider value={setTheme}>
  27. <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
  28. </SetThemeContext.Provider>
  29. );
  30. };