Learn to use the dark side of the Force

How to add dark mode to your React apps

While working on my personal portfolio page, I’ve spent a fair amount of time learning about the latest, most hyped, seriously mind-blowing subject in web development: dark mode. Why it took us 50 years to come up with this concept, I’m not entirely sure, but now that we finally figured it out, it’s here to stay since it’s objectively superior to bright white pages blinding you during your 3am browsing adventures. Darker colors, problem solved. Who knew?

There are several way to write dark mode into your React app, you can use , but I’ve found use-dark-mode by Donavon West to be the simplest implementation for basic concepts, especially when you’re adding this feature to existing code. It’s a custom React hook to help you create a “dark mode” component for your page. You can of course modify it to create any kind of toggled theme this way — business in the front, nyancats in the back, for example — , but the most obvious application is light and dark mode.

There are two ways you can implement use-dark-mode, but in either case you begin with the installation (react@16.8.0 or greater):

$ npm install use-dark-mode

Option 1: Toggle a CSS class onto an element (defaults to document.body). When you set up your CSS to display different views based on the presence of the selector, the following CSS is used in the to ease the background color in/out of dark mode.

body.light-mode {
background-color: #fff;
color: #333;
transition: background-color 0.3s ease;
body.dark-mode {
background-color: #1a1919;
color: #999;

Option 2: If you prefer to not use global classes, you can write an onChange handler and specify all details of the implementation yourself. Choose whichever method you feel more comfortable with or the one that best suits your existing code, both work equally well.

In version 2.x, the user setting persists to local storage and shares dark mode state with all other useDarkMode components on the page AND with all other tabs/browser windows. You can find additional tips, info, and demo apps , but it really is that simple.

You did it, you joined the dark side. Good. Let the success flow through you.

Software Engineer. Creature of Havoc.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store