Skip to content

Commit

Permalink
theme provider add listener for preference change
Browse files Browse the repository at this point in the history
  • Loading branch information
nickzoum committed Aug 5, 2022
1 parent 2e34737 commit edfe3b7
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/lib/themeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ if (storedMode) {
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [defaultTheme, setDefaultTheme] = useState(getDefaultBrowserTheme);
const [savedTheme, setSavedTheme] = useState(getSavedTheme);
const themeMode = savedTheme ?? getDefaultBrowserTheme();
const themeMode = savedTheme ?? defaultTheme;

const toggleThemeMode = useCallback(
function () {
Expand All @@ -42,6 +43,7 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
[themeMode]
);

// local storage change (if the theme was changed from another tab)
useEffect(() => {
window.addEventListener('storage', onStorageChange, false);
return () => window.removeEventListener('storage', onStorageChange, false);
Expand All @@ -51,6 +53,18 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
}
}, []);

// preference change (if the browser settings were changed)
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
mediaQuery.addEventListener('change', onPreferenceChange, false);
return () =>
mediaQuery.removeEventListener('change', onPreferenceChange, false);

function onPreferenceChange() {
setDefaultTheme(getDefaultBrowserTheme());
}
}, []);

// When the mode gets updated then update the document attribute
useEffect(() => {
if (savedTheme) {
Expand Down

0 comments on commit edfe3b7

Please sign in to comment.