-
-
Save sandeshdamkondwar/008a18cbef365d55c325b29fbba36de5 to your computer and use it in GitHub Desktop.
A custom React Hook to help you implement a "light/dark mode" component for your application.
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
html[data-theme='dark'] { | |
--text-color: #f0F0F0; | |
--background-body: #1C1C1C; | |
--other-var: #111111; | |
} | |
html[data-theme='light'] { | |
--text-color: #111111; | |
--background-body: #FAFAFA; | |
--other-var: #ffffff; | |
} | |
body { | |
color: var(--text-color); | |
background-color: var(--background-body); | |
} |
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
// hooks/use-theme.js | |
import { useState, useLayoutEffect } from 'react' | |
const preferDarkSchema = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches | |
const defaultTheme = preferDarkSchema ? 'dark' : 'light' | |
function useTheme() { | |
const [theme, setTheme] = useState(localStorage.getItem('theme') || defaultTheme) | |
useLayoutEffect(() => { | |
document.documentElement.setAttribute('data-theme', theme) | |
localStorage.setItem('theme', theme) | |
}, [theme]) | |
return { theme, setTheme } | |
} | |
export default useTheme |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment