1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-11-16 01:55:18 +01:00
blog/src/hooks/useDarkMode.ts

63 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-03-13 04:11:44 +01:00
//
// adapted from
// https://github.com/daveschumaker/react-dark-mode-hook/blob/master/useDarkMode.js
//
import { useState, useEffect, useCallback } from 'react'
const isClient = typeof window === 'object'
function getDarkMode() {
// if (localStorage.getItem('theme') === 'dark') {
// return true
// } else if (localStorage.getItem('theme') === 'light') {
// return false
// }
if (
isClient &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
return true
} else {
return false
}
}
export default function useDarkMode(): {
value: boolean
toggle?: () => void
} {
const [darkMode, setDarkMode] = useState(getDarkMode)
function toggleDarkMode() {
setDarkMode(!darkMode)
}
//
// Handle system theme change events
//
const handleChange = useCallback(() => {
setDarkMode(getDarkMode())
}, [])
useEffect(() => {
2021-03-13 04:56:07 +01:00
if (!isClient || process.env.NODE_ENV === 'test') return
2021-03-13 04:11:44 +01:00
const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
try {
darkModeQuery.addEventListener('change', handleChange)
} catch (addEventListenerError) {
console.error(addEventListenerError)
}
return () =>
window
.matchMedia('(prefers-color-scheme: dark)')
.removeEventListener('change', handleChange)
}, [handleChange])
return { value: darkMode, toggle: toggleDarkMode }
}