How to implement darkmode in NextJS
May 4, 2024
Installation
The simple way to implement darkmode in nextjs is using library called next-theme
so you need to install it first
Setup
in your app/layout.jsx
import ThemeProvider
from next-themes
and wrap the children with ThemeProvider
you can change the default theme with light
or dark
ThemeProvider is a client component, not a server component and you need to add suppressHydrationWarning
in your html because if not it will give you a warning.
CSS or Tailwind
You need to config first to make darkmode enable
With CSS
With Tailwind
in your tailwind.config.js
simply just set the darkMode property to class
Usage
remember to use useEffect
to make sure it is rendered in client component, Because we cannot know the theme on the server, many of the values returned from useTheme
will be undefined
until mounted on the client. This means if you try to render UI based on the current theme before mounting on the client, you will see a hydration mismatch error.
Thats it, you can check this for more information.