How to detect dark mode theme in React Material UI

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.

Using useMediaQuery() hook

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


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

Rate this post

Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.