This succinct and straight-to-the-point article shows you how to check whether the user’s system is in dark mode or light mode. Knowing that thing can help your React app automatically change its color scheme to suit your user’s wishes and lighting conditions. We’ll write some code with modern features of React including hooks and functional components (you won’t see old-fashioned stuff like class-based components).
Table of Contents
Overview
We watch the prefers-color-scheme CSS media feature to detect dark mode on the system setting level or browser setting level:
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', event => {
const colorScheme = event.matches ? "dark" : "light";
console.log(colorScheme); // "dark" or "light"
});
To understand how to apply this technique in a real-world React app with the useState and useEffect hooks, let’s examine the example below.
The Complete Example
App Preview
The tiny project we’re going to build displays the current color mode on the screen. When the system theme is light, the text is blue and the background is white. When the system theme is dark, the text is white and the background is dark grey.
A demo is worth more than a thousand words:
The Code
1. Create a brand new React project:
npx create-react-app kindacode-example
You can choose another name if you want.
2. Remove all of the default code in src/App.js then add the following:
// KindaCode.com
// src/App.js
import { useState, useEffect } from 'react'
function App() {
// This holds the information about dark mode/light mode
const [mode, setMode] = useState();
useEffect(() => {
window.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', event => {
const colorScheme = event.matches ? "dark" : "light";
console.log(colorScheme); // "dark" or "light"
setMode(colorScheme);
});
}, []);
return (
<div style={{ background: mode === 'dark' ? '#444' : '#fff', height: '100vh' }}>
<div style={{ padding: 30 }}>
<h1 style={{ color: mode === 'dark' ? '#fff' : '#2979ff' }}>
{mode === "dark" ? "Dark Mode" : "Light Mode"}
</h1>
</div>
</div>
);
}
export default App;
3. Get it up and running:
npm start
And go to http://localhost:3000 to check the result.
Conclusion
You’ve learned how to detect dark mode in React and walked through a full example of doing it in practice. If you’d like to explore more new and interesting stuff about the modern React development world, take a look at the following articles:
- React + TypeScript: Re-render a Component on Window Resize
- React + TypeScript: Making a Reading Progress Indicator
- React Router: How to Highlight Active Link
- How to Use Styled JSX in React: A Deep Dive
- React: Get the Position (X & Y) of an Element
- React + TypeScript: Multiple Dynamic Checkboxes
You can also check our React category page and React Native category page for the latest tutorials and examples.