How to make a flicker-free dark theme toggle with Next.js, TailwindCSS, and next-themes

Coner Murphy
9 min readOct 3, 2022
Photo from https://unsplash.com/photos/in9-n0JwgZ0

Have you ever added a theme toggle to a website? Have you also tried to remember the user’s preference so they see the same theme when they visit again?

Yes? Then my final question is, have you ever been greeted by a flash of the wrong theme on page load before switching to the correct theme after a few seconds?

Well, in this blog post I’m going to show you how to resolve just that. Today, we’re going to add a dark/light theme toggle to a Next.js application using TailwindCSS with no theme flickering at all. 🙌

Here is an example of what we will be creating from my website.

Next.js and TailwindCSS initial setup

To follow along in this tutorial you will already need to have a Next.js application up and running, if you don’t you can follow the Next.js documentation here. I will be using TypeScript in my project but you don’t have to, this tutorial will work absolutely fine with standard JavaScript.

Once you have your Next.js application up and running we need to install TailwindCSS…

--

--

Coner Murphy

Fullstack Developer | Technical Writer | Freelancer 👩‍💻 Tweets about Web Dev, Tech, Entrepreneurship 📈 Building In Public ➡ http://squares.so