Learn to use the dark side of the Force
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 styled components, 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 (
firstname.lastname@example.org 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 demo app to ease the background color in/out of dark mode.
transition: background-color 0.3s ease;
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 here, but it really is that simple.
You did it, you joined the dark side. Good. Let the success flow through you.