diff --git a/src/hooks/useThemeToggle.tsx b/src/hooks/useThemeToggle.tsx new file mode 100644 index 00000000..0e8a8aed --- /dev/null +++ b/src/hooks/useThemeToggle.tsx @@ -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 }; +}; diff --git a/tsconfig.json b/tsconfig.json index f1c8eb6b..df87d6f0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -20,6 +20,9 @@ "@utils/*": [ "src/utils/*" ], + "@hooks/*": [ + "src/hooks/*" + ], "@/*" : [ "./src/*" ]