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.