Created
October 30, 2020 11:42
-
-
Save byurhannurula/7d3242817a588e06ff157b04c83b51a2 to your computer and use it in GitHub Desktop.
React.js hook for light/dark theme
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react' | |
export const useColorMode = () => { | |
const [theme, setTheme] = useState( | |
window.localStorage.getItem('theme') || 'light', | |
) | |
const setNewTheme = (newTheme) => { | |
setTheme(newTheme) | |
window.localStorage.setItem('theme', newTheme) | |
document.documentElement.setAttribute('data-theme', newTheme) | |
} | |
const toggleTheme = () => { | |
if (theme === 'dark') { | |
setNewTheme('light') | |
} else { | |
setNewTheme('dark') | |
} | |
} | |
const prefersDarkMode = () => { | |
const query = window.matchMedia('(prefers-color-scheme: dark)') | |
if (query !== 'undefined' && query.matches) { | |
return true | |
} | |
return false | |
} | |
useEffect(() => { | |
const localTheme = window.localStorage.getItem('theme') | |
if (localTheme) { | |
setNewTheme(localTheme) | |
} else if (prefersDarkMode()) { | |
setNewTheme('dark') | |
} else { | |
setNewTheme('light') | |
} | |
}, []) | |
return [theme, toggleTheme] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment