react check if browser is in dark mode

React Check if Browser is in Dark Mode

When building a website or web application, it is important to provide a seamless user experience regardless of the user's preferences. One of these preferences is the choice between light and dark mode. In this article, we will look into how to check if the user's browser is in dark mode using React.

Method 1: Using CSS Media Query

The easiest way to detect if the user's browser is in dark mode is by using CSS media query. We can add a listener to the window.matchMedia() function to check if the prefers-color-scheme media query matches with the 'dark' keyword.

const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;

if (prefersDarkMode) {
  document.body.classList.add('dark-mode');
} else {
  document.body.classList.remove('dark-mode');
}

In this example, we are using the classList property to add or remove the dark-mode class to the body element, which can be used to apply specific styles for dark mode.

Method 2: Using React Hooks and State

We can also use React hooks and state to check if the user's browser is in dark mode. We can create a custom hook called useDarkMode() that listens to changes in the prefers-color-scheme media query and updates the state accordingly.

import { useEffect, useState } from 'react';

function useDarkMode() {
  const [isDarkMode, setIsDarkMode] = useState(false);

  useEffect(() => {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    setIsDarkMode(mediaQuery.matches);

    const handler = () => setIsDarkMode(mediaQuery.matches);
    mediaQuery.addListener(handler);

    return () => mediaQuery.removeListener(handler);
  }, []);

  return isDarkMode;
}

function App() {
  const isDarkMode = useDarkMode();

  return (
    <div className={isDarkMode ? 'dark-mode' : ''}>
      <p>This is my content</p>
    </div>
  );
}

In this example, we are using the useEffect() hook to add and remove event listeners to the prefers-color-scheme media query. We update the state of isDarkMode whenever the media query matches or changes.

We can then use the isDarkMode state to conditionally render our components based on whether the user's browser is in dark mode or not.

Conclusion

Detecting if the user's browser is in dark mode is an important part of providing a seamless user experience. We can use CSS media queries or React hooks and state to check for the user's preference and update our application accordingly.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe