This article already presumes you have a Next.js project set up. If you don't have one, quickly set up a new one by running: next-themes is a wid

Dark Mode in Next.js in 5 minutes

submited by
Style Pass
2024-12-13 15:30:07

This article already presumes you have a Next.js project set up. If you don't have one, quickly set up a new one by running:

next-themes is a widely adopted leightweight library that makes it easy to add a dark mode to your Next.js app. It saves you from the hassle and it works out of the box with different CSS configurations, it can also work with Tailwind.

next-themes provides us with a useTheme hook that we can use to switch between themes. We can create a simple component that will allow us to utilize that functionallity and switch between dark/light theme. Since hooks can only run on client components, make sure you add "use client"; at the top of the file. One other thing to note as stated in the next-themes docs as well:

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.

This is why we added the useEffect and mounted state to make sure the component is mounted and avoid any hydration mismatch errors.

Leave a Comment