Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create useThemeToggle hook in new hooks directory and add import alias #273

Merged
merged 1 commit into from
Apr 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/hooks/useThemeToggle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useEffect } from 'react';

const disableTransitions = () => {
const css = document.createElement('style');
css.textContent = `
* {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}
`;
document.head.appendChild(css);
requestAnimationFrame(() => {
document.head.removeChild(css);
});
};

export const useThemeToggle = () => {
const toggleTheme = () => {
const currentTheme =
localStorage.getItem('themeToggle') ||
(window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';

disableTransitions();

document.documentElement.classList.toggle('dark', newTheme === 'dark');
localStorage.setItem('themeToggle', newTheme);
};

return { toggleTheme };
};
3 changes: 3 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
"@utils/*": [
"src/utils/*"
],
"@hooks/*": [
"src/hooks/*"
],
"@/*" : [
"./src/*"
]
Expand Down