Skip to content

Commit

Permalink
Merge pull request #1173 from sahil9001/system-theme-unless-set
Browse files Browse the repository at this point in the history
feat: added theme check unless already set
  • Loading branch information
dartpain authored Oct 1, 2024
2 parents 872b390 + 1e7fa98 commit 0475e55
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions frontend/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,34 @@ export function useMediaQuery() {
}

export function useDarkTheme() {
const [isDarkTheme, setIsDarkTheme] = useState<boolean>(
localStorage.getItem('selectedTheme') === 'Dark' || false,
);
const getSystemThemePreference = () => {
return (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
);
};

const getInitialTheme = () => {
const storedTheme = localStorage.getItem('selectedTheme');
if (storedTheme === 'Dark' || storedTheme === 'Light') {
return storedTheme === 'Dark';
}
return getSystemThemePreference();
};

const [isDarkTheme, setIsDarkTheme] = useState<boolean>(getInitialTheme());

useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
if (localStorage.getItem('selectedTheme') === null) {
setIsDarkTheme(mediaQuery.matches);
}
};

mediaQuery.addListener(handleChange);
return () => mediaQuery.removeListener(handleChange);
}, []);

useEffect(() => {
localStorage.setItem('selectedTheme', isDarkTheme ? 'Dark' : 'Light');
Expand All @@ -79,9 +104,9 @@ export function useDarkTheme() {
}
}, [isDarkTheme]);

const toggleTheme: any = () => {
const toggleTheme = () => {
setIsDarkTheme(!isDarkTheme);
};

return [isDarkTheme, toggleTheme];
return [isDarkTheme, toggleTheme] as const;
}

0 comments on commit 0475e55

Please sign in to comment.