I am a huge fan of Josh W Comeau's website as well as the content that he puts out. He has some very, very interesting articles, but by far the most interesting one is about his Quest for The Perfect Dark Mode.
It is a perfect read, equal parts technical and entertaining and quite frankly, an inspiration for how a technical blog post should be written. I've read it in its entirety more than thrice, and at the end of the third read, I just knew that I had to try it out.
Here's the small problem though: Josh implemented it in Gatsby. Meanwhile, my blog is built using Next.js. (Both of these implement static-ish websites with React, I write more about this in my previous blog post)
If you haven't already, please go through Josh's post first if you want to be able to follow along. Well, into uncharted waters we go!
So what's the big deal? What really is the perfect dark mode?
If you take a look at a website which has support for dark mode like mdxjs.com, you'll notice something if you try to refresh the page once you've enabled dark mode.
The dreaded flicker of light mode. ugh.
So why does this happen?
This is a problem that is not limited to static/hybrid websites but extends to pretty much any website that uses JavaScript to "hydrate" its components. This is because when our page loads up, here's that happens:
transparent
background color, which means that you'll get a white background unless you're using certain extensionsSo what should we do? We need to find a way to be able to run some code and apply the appropriate background-color
(and by extension, the theme) before the entire page has loaded.
Here's a rough list of what we need to implement:
Let's start by putting together a simple Next.js page with a pretty basic dark mode toggle:
JSX1// pages/index.js2import { useState } from "react";34const IndexPage = () => {5 const [isDarkTheme, setIsDarkTheme] = useState(false);67 const handleToggle = (event) => {8 setIsDarkTheme(event.target.checked);9 };10 return (11 <div>12 <label>13 <input14 type="checkbox"15 checked={isDarkTheme}16 onChange={handleToggle}17 />{" "}18 Dark19 </label>20 <h1>Hello there</h1>21 <p>General Kenobi!</p>22 </div>23 );24};2526export default IndexPage;
Let's begin by adding the ability to store and retrieve the preference if the user has already visited our website before. localStorage is a really simple way of accomplishing exactly this, even when a user refreshes the page or closes the browser completely and opens it again at a later time. Although there are concerns over storing sensitive and/or large data in localStorage, it is perfect for storing our user's dark mode preference.
Here's how we can save and load our theme
preference using localStorage
:
JS1window.localStorage.setItem("theme", "dark"); // or "light"23const userPreference = window.localStorage.getItem("theme"); // "dark"
prefers-color-scheme is a CSS media feature that allows us to detect if the user has set any system-wide dark mode preferences, which we can use in case the user hasn't set a preference yet.
All we need to do is run a CSS media query, and the browser provides us with matchMedia()
to do exactly this!
Here's what a media query to check if the user has set any preference looks like:
JS1const mql = window.matchMedia("(prefers-color-scheme: dark)");
with the output (when the user has set a preference for dark mode):
JSON1{2 "matches": true,3 "media": "(prefers-color-scheme: dark)"4}
Let's add these to our app
JSX1import { useState } from "react";23const IndexPage = () => {4 const [isDarkTheme, setIsDarkTheme] = useState(false);56 const handleToggle = (event) => {7 setIsDarkTheme(event.target.checked);8 };910 const getMediaQueryPreference = () => {11 const mediaQuery = "(prefers-color-scheme: dark)";12 const mql = window.matchMedia(mediaQuery);13 const hasPreference = typeof mql.matches === "boolean";1415 if (hasPreference) {16 return mql.matches ? "dark" : "light";17 }18 };1920 const storeUserSetPreference = (pref) => {21 localStorage.setItem("theme", pref);22 };23 const getUserSetPreference = () => {24 return localStorage.getItem("theme");25 };2627 useEffect(() => {28 const userSetPreference = getUserSetPreference();29 if (userSetPreference !== null) {30 setIsDarkTheme(userSetPreference === "dark");31 } else {32 const mediaQueryPreference = getMediaQueryPreference();33 setIsDarkTheme(mediaQueryPreference === "dark");34 }35 }, []);36 useEffect(() => {37 if (isDarkTheme !== undefined) {38 if (isDarkTheme) {39 storeUserSetPreference("dark");40 } else {41 storeUserSetPreference("light");42 }43 }44 }, [isDarkTheme]);4546 return (47 <div>48 <label>49 <input50 type="checkbox"51 checked={isDarkTheme}52 onChange={handleToggle}53 />{" "}54 Dark55 </label>56 <h1>Hello there</h1>57 <p>General Kenobi!</p>58 </div>59 );60};6162export default IndexPage;
IndexPage
component has been mounted, we retrieve the user's set preference if they've already set one from their earlier visitlocalStorage.getItem()
call returns null
if they haven't set one, and we move on to checking their system wide preference is dark modelocalStorage
for future useGreat! We've got a toggle working, and we're also able to store and retrieve the correct state in our page
The biggest challenge (surprisingly) was being able to run all these checks before anything is shown to the user. Since we're using Next.js with its Static Generation, there's no way for us to know at code/build time what the user's preference is going to be 🤷♂️
Unless...there was a way run some code before all of our page is loaded and rendered to the user!
Take a look at the code below:
HTML1<body>2 <script>3 alert("No UI for you!");4 </script>5 <h1>Page Title</h1>6</body>
Here's what it looks like:
When we add a <script>
in our body before our <h1>
content, the rendering of the actual content is blocked by the script. This means that we can run code that will be guaranteed to run before any content is shown to the user, which is exactly what we wanna do!
From the example above, we know now that we need to add a <script>
in the <body>
of our page before the actual content.
Next.js provides a super sweet and easy way of modifying the <html>
and <body>
tags in our app by adding a _document.tsx
(or _document.js
) file. The Document
is only rendered in the server, so our script is loaded as we describe it on the client browser.
Using this, here's how we can add our script:
JSX1import Document, {2 Html,3 Head,4 Main,5 NextScript,6} from "next/document";78export default class MyDocument extends Document {9 render() {10 return (11 <Html>12 <Head />13 <body>14 <script15 dangerouslySetInnerHTML={{16 __html: customScript,17 }}18 ></script>19 <Main />20 <NextScript />21 </body>22 </Html>23 );24 }25}2627const customScript = `28 console.log("Our custom script runs!");29`;
The browser DOM provides us with innerHTML
to get or set the HTML contained within an element. Usually, setting HTML from code is risky business because it is easy to inadvertently expose users to a cross-site scripting (XSS) attack. React protects us from this by default, by sanitising the contents before rendering it.
If a user tries to set their name to <script>I'm dangerous!</script>
, React encodes characters like <
into <
. This way, the script has no effect.
React also provides a way to override this behaviour using dangerouslySetInnerHTML
, reminding us that it is dangerous. Well, in our use case, we actually do want to inject and run a script.
We're almost there!
We now know how to make sure that our script is loaded before the rest of the page (and with the help of Next.js' Document
, before any page), but we still need a couple more pieces of this puzzle:
background-color
and other CSS properties based on all the logic we'll add!The next piece of our puzzle is figuring out how to run our custom script as soon as possible.
As a reminder, we're doing this to figure out the correct state of dark mode (activated/deactivated, or more simply, true
/false
) to avoid any ungodly "flashes" of toggling when the user loads up our webpage.
Enter Immediately Invoked Function Expressions! (or IIFEs for short)
An IIFE is simply a JavaScript function that is executed as soon as it is defined. Aside from having the benefit of being run Immediately upon definition, IIFEs are also great when one wants to avoid polluting the global namespace — something that we can definitely use since we have no use for our logic once it has run and set the apt mode.
Here's what an IIFE looks like:
JS1(function () {2 var name = "Sreetam Das";3 console.log(name);4 // "Sreetam Das"5})();67// Variable name is not accessible from the outside scope89console.log(name);10// throws "Uncaught ReferenceError: name is not defined"
Let's add this to our _document.js
JSX1import Document, {2 Html,3 Head,4 Main,5 NextScript,6} from "next/document";78function setInitialColorMode() {9 function getInitialColorMode() {10 const preference = window.localStorage.getItem("theme");11 const hasExplicitPreference = typeof preference === "string";1213 /**14 * If the user has explicitly chosen light or dark,15 * use it. Otherwise, this value will be null.16 */17 if (hasExplicitPreference) {18 return preference;19 }2021 // If there is no saved preference, use a media query22 const mediaQuery = "(prefers-color-scheme: dark)";23 const mql = window.matchMedia(mediaQuery);2425 const hasImplicitPreference = typeof mql.matches === "boolean";26 if (hasImplicitPreference) {27 return mql.matches ? "dark" : "light";28 }2930 // default to 'light'.31 return "light";32 }3334 const colorMode = getInitialColorMode();35}3637// our function needs to be a string38const blockingSetInitialColorMode = `(function() {39 ${setInitialColorMode.toString()}40 setInitialColorMode();41})()42`;4344export default class MyDocument extends Document {45 render() {46 return (47 <Html>48 <Head />49 <body>50 <script51 dangerouslySetInnerHTML={{52 __html: blockingSetInitialColorMode,53 }}54 ></script>55 <Main />56 <NextScript />57 </body>58 </Html>59 );60 }61}
We're now able to correctly retrieve the appropriate state of our dark mode before the page loads completely! Our final hurdle is now being able to pass this on to our page's component so that we can actually apply the preferred dark mode state.
The challenge here is that we need to be able to transfer this piece of information from a pure JS script which is being run before the page and its React components have been loaded completely, and "hydrate" them.
The last step is to update our page with the user's preferred theme.
There are multiple ways to go about this:
we can use CSS classes for different themes, and switch them programmatically
we can use React's state
and pass a .class
as a template literal
we can also use styled-components
While all of the options seem like possible solutions, they each require a lot more boilerplate to be added
or we could CSS variables!CSS Custom Properties (also referred to as CSS Variables) allow us to reuse specific values throughout a document. These can be set using custom property notation and accessed using the var()
function like so:
CSS1:root {2 --color-primary-accent: #5b34da;3}
The best part about CSS variables is that they are reactive, they remain live throughout the lifetime of the page, and updating them updates the HTML that references them instantly. And they can be updated using JavaScript!
JSX1// setting2const root = document.documentElement;3root.style.setProperty("--initial-color-mode", "dark");45// getting6const root = window.document.documentElement;7const initial = root.style.getPropertyValue("--initial-color-mode");8// "dark"
CSS variables really shine when you want to have to reuse certain values in your CSS; my website uses a few that you can check out
We can use HTML attributes and since CSS also has access to these attributes, we can assign different values to CSS variables depending on the data-theme
attribute that we set, like so:
CSS1:root {2 --color-primary-accent: #5b34da;3 --color-primary: #000;4 --color-background: #fff;5 --color-secondary-accent: #358ef1;6}78[data-theme="dark"] {9 --color-primary-accent: #9d86e9;10 --color-secondary-accent: #61dafb;11 --color-primary: #fff;12 --color-background: #000;13}1415[data-theme="batman"] {16 --color-primary-accent: #ffff00;17}
and we can set and remove the attribute pretty easily too:
JSX1if (userPreference === "dark")2 document.documentElement.setAttribute("data-theme", "dark");34// and to remove, setting the "light" mode:5document.documentElement.removeAttribute("data-theme");
Finally, we're now able to pass on the computed dark mode state from our blocking script to our React component.
Before we put together everything we have so far, let's recap:
as soon as the webpage is being loaded, we inject and run a blocking script using Next.js' Document and IIFEs
check for user's saved preference from a previous visit using localStorage
check if the user has a system-wide dark mode preference using a CSS media query
if both above checks are inconclusive, we default to a light theme
pass this preference as a CSS variable, which we can read in our toggle component
the theme can be toggled, and upon toggling we save the preference for future visits
we should never have the flicker on the first load, even if the user has a preference for the non-default theme
we should always show the correct state of our toggle, and defer rendering the toggle if the correct state is unknown
Here's what the final result looks like:
JSX1import Document, {2 Html,3 Head,4 Main,5 NextScript,6} from "next/document";78function setInitialColorMode() {9 function getInitialColorMode() {10 const preference = window.localStorage.getItem("theme");11 const hasExplicitPreference = typeof preference === "string";1213 /**14 * If the user has explicitly chosen light or dark,15 * use it. Otherwise, this value will be null.16 */17 if (hasExplicitPreference) {18 return preference;19 }2021 // If there is no saved preference, use a media query22 const mediaQuery = "(prefers-color-scheme: dark)";23 const mql = window.matchMedia(mediaQuery);2425 const hasImplicitPreference = typeof mql.matches === "boolean";26 if (hasImplicitPreference) {27 return mql.matches ? "dark" : "light";28 }2930 // default to 'light'.31 return "light";32 }3334 const colorMode = getInitialColorMode();35 const root = document.documentElement;36 root.style.setProperty("--initial-color-mode", colorMode);3738 // add HTML attribute if dark mode39 if (colorMode === "dark")40 document.documentElement.setAttribute("data-theme", "dark");41}4243// our function needs to be a string44const blockingSetInitialColorMode = `(function() {45 ${setInitialColorMode.toString()}46 setInitialColorMode();47})()48`;4950export default class MyDocument extends Document {51 render() {52 return (53 <Html>54 <Head />55 <body>56 <script57 dangerouslySetInnerHTML={{58 __html: blockingSetInitialColorMode,59 }}60 ></script>61 <Main />62 <NextScript />63 </body>64 </Html>65 );66 }67}
Note how we use style.setProperty()
as well as documentElement.setAttribute()
to pass our data
Let's add our CSS, adding separate values for our CSS variables when dark mode is applied
CSS1:root {2 --color-primary-accent: #5b34da;3 --color-primary: #000;4 --color-background: #fff;5}67[data-theme="dark"] {8 --color-primary-accent: #9d86e9;9 --color-primary: #fff;10 --color-background: #000;11}1213body {14 background-color: var(--color-background);15 color: var(--color-primary);16}
Great! Now we need to import these styles into our application.
Since we want these styles to be available throughout our website, we'll need to use the App
component that Next.js provides us. This is similar to the Document
that we saw earlier, in that it's a special component which can be used to control each page in Next.js app as it's used to initialise our pages.
This makes it the correct place for adding our global CSS as well!
JSX1import "../styles.css";23export default function MyApp({ Component, pageProps }) {4 return <Component {...pageProps} />;5}
and finally, our React component page:
JSX1import { useEffect, useState } from "react";23const IndexPage = () => {4 const [darkTheme, setDarkTheme] = useState(undefined);56 const handleToggle = (event) => {7 setDarkTheme(event.target.checked);8 };9 const storeUserSetPreference = (pref) => {10 localStorage.setItem("theme", pref);11 };1213 const root = document.documentElement;14 useEffect(() => {15 const initialColorValue = root.style.getPropertyValue(16 "--initial-color-mode"17 );18 setDarkTheme(initialColorValue === "dark");19 }, []);20 useEffect(() => {21 if (darkTheme !== undefined) {22 if (darkTheme) {23 root.setAttribute("data-theme", "dark");24 storeUserSetPreference("dark");25 } else {26 root.removeAttribute("data-theme");27 storeUserSetPreference("light");28 }29 }30 }, [darkTheme]);3132 return (33 <div>34 {darkTheme !== undefined && (35 <label>36 <input37 type="checkbox"38 checked={darkTheme}39 onChange={handleToggle}40 />{" "}41 Dark42 </label>43 )}44 <h1>Hello there</h1>45 <p style={{ color: "var(--color-primary-accent)" }}>46 General Kenobi!47 </p>48 </div>49 );50};5152export default IndexPage;
Of course, there are packages which can handle all of this for you including "the flash" which differ only slightly in their implementation (Donavon here uses the .class
method). Also, here's a great article about the Principles of Dark UI Design that I would recommend you check out — it is a great read about the multiple challenges that one needs to take care of while implementing the perfect dark mode.
At the end of the day there are more and more people adding dark mode to their websites, and hopefully my journey here is able to help implement the perfect one for your website too.
Notice any typos? Have something to say or improvements to add? Feel free to reach out to me on Twitter and maybe even share this post using the button below :)
Published: November 22, 2020
No views yet. Wait what, How? 🤔