Last updated on Oct 15, 2022 by Suraj Sharma
In this tutorial, you will learn how you can use a custom React hook useMediaQuery
provided by the react material ui core module to check if dark mode is enabled on your browser.
React material ui core module @mui/material
exports the useMediaQuery()
custom hook to check whether a given CSS media query string is applied or not. It returns a boolean
value.
To detect if dark theme is enabled we have to pass (prefers-color-scheme: dark)
media query string as an argument to the useMediaQuery()
hook
Example:
import React from 'react';
import useMediaQuery from '@mui/material/useMediaQuery';
const DetectDarkMode = () => {
const isDarkModeEnabled = useMediaQuery('(prefers-color-scheme: dark)');
return (
<p>{`Dark mode is enabled: ${isDarkModeEnabled}`}</p>
);
}
Related Solutions
How to get React material ui theme object in function components
How to change font family of typography in React Material UI
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.