Detecting Browser Dark Theme in React 2024-01-23
Here's a hook that will return true
if the dark theme is on in the browser, or false
otherwise.
./use-is-dark-theme.hook.ts
import { useEffect, useState } from "react"
export const useIsDarkTheme = () => {
const [isDarkTheme, setIsDarkTheme] = useState(false)
useEffect(() => {
const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
const handleDarkModeChange = (event: MediaQueryListEvent) => setIsDarkTheme(event.matches)
setIsDarkTheme(darkModeMediaQuery.matches)
darkModeMediaQuery.addEventListener("change", handleDarkModeChange)
return () => darkModeMediaQuery.removeEventListener("change", handleDarkModeChange)
}, [])
return isDarkTheme
}