Skip to content

Commit

Permalink
feat(dark-mode): preserved dark mode state using local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
SUNNYKUMAR1232 committed Oct 17, 2023
1 parent f1281e3 commit 549e8cc
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
32 changes: 24 additions & 8 deletions client/src/context/ThemeContext.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import React, { useContext, useEffect, useState } from 'react';

import { ThemeProvider } from '@mui/material/styles';

import darkTheme from '../config/themes/dark';
import lightTheme from '../config/themes/light';

import useLocalStorage from '../hooks/useLocalStorage';
//context for theming
export const ThemeContext = React.createContext({
isDarkTheme: undefined,
Expand All @@ -15,12 +13,30 @@ export const useTheme = () => useContext(ThemeContext);

//context provider
const ThemeContextProvider = ({ children }) => {
const [isDarkTheme, setDarkTheme] = useState(false);

const [defaultTheme, setDefaultTheme] = useLocalStorage('DefaultTheme');
const [isDarkTheme, setDarkTheme] = useLocalStorage('IsDarkTheme');
useEffect(() => {}, [isDarkTheme]);
useEffect(() => {
const currentHour = new Date().getHours();
setDarkTheme(currentHour >= 20 || currentHour <= 8 ? true : false);
}, [setDarkTheme]);
const darkModeMediaQuery = window.matchMedia(
'(prefers-color-scheme: dark)',
);
const setTheme = (event) => {
if (event.matches) {
setDefaultTheme(defaultTheme === true ? defaultTheme : null);
setDarkTheme(true);
} else {
setDefaultTheme(false);
setDarkTheme(defaultTheme === false ? defaultTheme : null);
}
};
setTheme(darkModeMediaQuery);
darkModeMediaQuery.addEventListener('change', setTheme);
setDarkTheme(isDarkTheme);
setDefaultTheme(isDarkTheme ? isDarkTheme : isDarkTheme);
return () => {
darkModeMediaQuery.removeEventListener('change', setTheme);
};
}, [isDarkTheme]);

return (
<ThemeContext.Provider value={{ isDarkTheme, setDarkTheme }}>
Expand Down
26 changes: 26 additions & 0 deletions client/src/hooks/useLocalStorage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useState } from 'react';

const useLocalStorage = (key, initialValue) => {
const [state, setState] = useState(() => {
try {
const value = window.localStorage.getItem(key);
return value != 'null' ? JSON.parse(value) : initialValue;
} catch (error) {
console.log(error);
}
});

const setValue = (value) => {
try {
const valueToStore = value instanceof Function ? value(state) : value;
window.localStorage.setItem(key, JSON.stringify(valueToStore));
setState(value);
} catch (error) {
console.log(error);
}
};

return [state, setValue];
};

export default useLocalStorage;

0 comments on commit 549e8cc

Please sign in to comment.