Skip to content

Instantly share code, notes, and snippets.

@viclafouch
Last active June 23, 2020 16:43
Show Gist options
  • Save viclafouch/08e76fe57fbebfb89ee9263fe9de406f to your computer and use it in GitHub Desktop.
Save viclafouch/08e76fe57fbebfb89ee9263fe9de406f 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.
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);
}
// 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