No-brainer Dark Mode for Next.js

TIL: @pacocoursey next-themes. I've been pretty happy using @tailwindCSS and letting the system render the right theme for the user, but if you do want to add UI controls. Give this no-brainer a shot, here's how I did mine.

Set the provider and attribute to display the active theme as a class. This will enable all dark classes present in the HTML tree. Don't forget to declare this in your @tailwindCSS config file: module.exports = { darkMode: 'class' }:

To consume and toggle the UI, use their useTheme hook. To avoid hydration errors, return a loading state of your choice until fully mounted:

It is that simple. It has 74,528 weekly npm downloads and if it’s good enough for @leeerob, it’s good for me too. Get creative with your loading state and toggle button (or not && KISS). Check out their next-themes GH repo for more info.

--

--

From 🇭🇳 https://hectorsosa.me

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