Skip to content

Instantly share code, notes, and snippets.

Last active June 23, 2020 16:43
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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