Adding Dark Mode to your NextJS App with TailwindCSS

Juan Zapata Gomez

Juan Zapata Gomez / January 15, 2022

2 min read

Dark Mode Cover

Why Dark Mode?

Dark mode has become an increasingly popular feature and it's not going away any time soon. Many of the products we use today include an option for enabling dark mode in one way or another. Personally, I really enjoy dark mode and most of the apps on my phone have Dark Mode enabled. Dark mode not only looks good it also helps save battery life. The real question is, why shouldn't you use dark mode?

Technologies: Next-Themes & TailwindCSS

next-themes enables developers to add Dark Mode capabilities to your NextJS app with just a few lines of code.

If you're not yet familiar with tailwindcss, its a CSS Framework that makes building UI applications a piece of cake.

next-themes pairs very well with tailwindcss and that's exactly what we will be using in this tutorial.

Install Next-Themes

$ npm install next-themes
# or
$ yarn add next-themes

Adding Dark Mode

pages/_app.js
import { ThemeProvider } from 'next-themes'

function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider attribute="class">
      <Component {...pageProps} />
    </ThemeProvider>
  )
}

export default MyApp
tailwind.config.js
module.exports = {
  darkMode: 'class'
}

Using Dark Mode

Since a server is unable to know the theme, the client must be mounted first in order to prevent a hydration mismatch error.

import { useTheme } from 'next-themes'

const ToggleTheme = () => {
  const [mounted, setMounted] = useState(false)
  const { resolvedTheme, setTheme } = useTheme()

  useEffect(() => setMounted(true), [])

  if (!mounted) return null

  return (
    // Add TailwindCSS `dark:` option
    <div classname="text-black dark:text-white">
      The current theme is: {resolvedTheme}
      <button onClick={() => setTheme('light')}>Light Mode</button>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
    </div>
  )
}