Skip to content

Commit

Permalink
use/read/write theme mode
Browse files Browse the repository at this point in the history
  • Loading branch information
nickzoum committed Aug 3, 2022
1 parent 07640df commit c7f0f99
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/lib/useThemeMode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';

export type ThemeMode = 'light' | 'dark';
const storageName = 'themeMode';
const attributeName = 'data-theme-mode';

export function useTheme() {
const [theme, setTheme] = useState(getTheme());

useEffect(() => {
const listener = function () {
setTheme(getTheme());
};
window.addEventListener('load', listener);

return () => window.removeEventListener('load', listener);
}, []);

return theme;
}

export function getTheme() {
return localStorage.getItem(storageName) ?? getCSSTheme();
}

export function setTheme(mode: ThemeMode) {
document.documentElement.setAttribute(attributeName, mode);
localStorage.setItem(storageName, mode);
}

export function getCSSTheme(): ThemeMode {
return getComputedStyle(document.documentElement)
.getPropertyValue('--theme')
.replace(/^\s+|\s+$/g, '') as ThemeMode;
}

0 comments on commit c7f0f99

Please sign in to comment.