Skip to content

Commit

Permalink
feat: remove onChange
Browse files Browse the repository at this point in the history
  • Loading branch information
ianzone committed Aug 22, 2024
1 parent c8a9cc5 commit 2d2f1d6
Showing 1 changed file with 4 additions and 10 deletions.
14 changes: 4 additions & 10 deletions packages/hooks/src/useTheme/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,18 @@ export type ThemeType = 'light' | 'dark';

const matchMedia = window.matchMedia('(prefers-color-scheme: dark)');

type Callback = (theme: ThemeType) => void;

function useCurrentTheme(callback: Callback = () => {}) {
function useCurrentTheme() {
const [theme, setTheme] = useState<ThemeType>(() => {
const init = matchMedia.matches ? ThemeMode.DARK : ThemeMode.LIGHT;
callback(init);
return init;
});

useEffect(() => {
const onThemeChange: MediaQueryList['onchange'] = (event) => {
if (event.matches) {
setTheme(ThemeMode.DARK);
callback(ThemeMode.DARK);
} else {
setTheme(ThemeMode.LIGHT);
callback(ThemeMode.LIGHT);
}
};

Expand All @@ -38,18 +33,17 @@ function useCurrentTheme(callback: Callback = () => {}) {
return () => {
matchMedia.removeEventListener('change', onThemeChange);
};
}, [callback]);
}, []);

return theme;
}

type Options = {
localStorageKey?: string;
onChange?: Callback;
};

export default function useTheme(options: Options = {}) {
const { localStorageKey, onChange } = options;
const { localStorageKey } = options;

const [themeMode, setThemeMode] = useState<ThemeModeType>(() => {
const preferredThemeMode =
Expand All @@ -66,7 +60,7 @@ export default function useTheme(options: Options = {}) {
}
};

const currentTheme = useCurrentTheme(onChange);
const currentTheme = useCurrentTheme();
const theme = themeMode === ThemeMode.SYSTEM ? currentTheme : themeMode;

return {
Expand Down

0 comments on commit 2d2f1d6

Please sign in to comment.