React detect dark mode code example
Example: react check if browser is in dark mode
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
const newColorScheme = e.matches ? "dark" : "light";
});
const [mode, setMode] = useState<"light" | "dark" | undefined>(
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? "dark" :"light"
);
useEffect(() => {
const modeMe = (e: any) => {
setMode(e.matches ? "dark" : "light");
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', modeMe);
return window.matchMedia('(prefers-color-scheme: dark)').removeListener(modeMe);
}, []);