Last active
March 1, 2021 20:09
-
-
Save EdPike365/d4a66d56b1575985d19c71a51f4d256c to your computer and use it in GitHub Desktop.
React Hook to detect Dark Mode preference
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
import React, { useEffect, useState } from "react" | |
//This will show the "prefers-color-scheme" value for this browser, reactively | |
//NOTE: Hook functions must use camel case because of linting rules. | |
function DarkModePreferredStatus() { | |
//NOTES ON INTERACTIONS WITH CHROME DEV TOOLS: | |
//On Windows 10, Chrome gets its settings from the OS via Settings> Colors | |
// options: light, dark, custom | |
//This value can be overridden using Chrome dev tools emulator | |
// options: no-preference, light, dark | |
//TODO: If 2 browser tabs are open on pages with this widget, when Chrome emulator settings change | |
//it only changes the text value in the tab that has the debugger open. However, the browser media value changes | |
//and any theme change will take affect on both tabs even though the string does not change. | |
const [prefersDarkMode, setPrefersDarkMode] = useState( | |
window.matchMedia("(prefers-color-scheme: dark)").matches | |
) | |
useEffect(() => { | |
function handleDarkModePrefferedChange() { | |
const doesMatch = window.matchMedia("(prefers-color-scheme: dark)").matches | |
setPrefersDarkMode(doesMatch) | |
} | |
window | |
.matchMedia("(prefers-color-scheme: dark)") | |
.addEventListener("change", handleDarkModePrefferedChange) | |
//good house keeping to remove listener, good article here https://www.pluralsight.com/guides/how-to-cleanup-event-listeners-react | |
return () => { | |
window | |
.matchMedia("(prefers-color-scheme: dark)") | |
.removeEventListener("change", handleDarkModePrefferedChange) | |
} | |
}, []) | |
return prefersDarkMode | |
} | |
const DarkModeBrowserPref = () => { | |
const prefersDarkMode = DarkModePreferredStatus() | |
return <div>{` Prefers Dark Mode = ${prefersDarkMode}. `}</div> | |
} | |
export default DarkModeBrowserPref |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment