Skip to content

Instantly share code, notes, and snippets.

@knjname
Created November 27, 2019 06:12
Show Gist options
  • Save knjname/b8f6826ca5915e430bc99139a9663f85 to your computer and use it in GitHub Desktop.
Save knjname/b8f6826ca5915e430bc99139a9663f85 to your computer and use it in GitHub Desktop.
A react hook for DarkMode detection.
import { useEffect, useState } from "react";
const darkModeQuery = matchMedia("(prefers-color-scheme: dark)");
export const useDarkMode = () => {
const [isDark, setDark] = useState(darkModeQuery.matches);
useEffect(() => {
const listener = () => {
console.log("Dark mode changed", darkModeQuery.matches);
setDark(darkModeQuery.matches);
};
darkModeQuery.addListener(listener);
return () => {
darkModeQuery.removeListener(listener);
};
});
return isDark;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment