Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing
The next-themes
package is an abstraction for themes in your Next.js app. It provides several key features such as perfect dark mode in just 2 lines of code, system setting with prefers-color-scheme
, themed browser UI with color-scheme
, support for Next.js 13 appDir, no flash on load (both SSR and SSG), sync theme across tabs and windows, disable flashing when changing themes, force pages to specific themes, class or data attribute selector, and a useTheme
hook.
To install and use next-themes
, follow these steps:
Add the next-themes
package to your Next.js app by running the following command in your terminal:
npm install next-themes
In your app’s custom _app.js
file, import the ThemeProvider
component from next-themes
and wrap your app with it:
// Import the ThemeProvider component
import { ThemeProvider } from 'next-themes';
// Wrap your app with the ThemeProvider
function MyApp({ Component, pageProps }) {
return (
<ThemeProvider>
<Component {...pageProps} />
</ThemeProvider>
);
}
export default MyApp;
Optionally, you can add support for dark mode in your layout file (layout.jsx
) by following these steps:
a. Create a new file for the providers component (e.g., ThemeProviders.jsx
) and import the useTheme
hook from next-themes
:
import { useTheme } from 'next-themes';
export function ThemeProviders() {
const { theme } = useTheme();
return (
<>
{/* your providers */}
</>
);
}
b. Import the ThemeProviders
component in your layout file and include it within the <body>
tag:
import { ThemeProviders } from './ThemeProviders';
function Layout({ children }) {
return (
<div>
<ThemeProviders />
{/* your layout content */}
</div>
);
}
export default Layout;
Ensure that you add suppressHydrationWarning
to the <html>
element in your pages/_document.js
file to avoid any warnings:
// In your _document.js file
<html suppressHydrationWarning={true} lang="en">
You can now utilize the theme in your HTML and CSS. The default behavior modifies the data-theme
attribute on the <html>
element, which you can use for styling. If you prefer using the class attribute, set the attribute
property of the ThemeProvider
to class
.
In summary, next-themes
is a convenient package for implementing themes in your Next.js app. It provides easy dark mode support, system color scheme integration, themed browser UI, and various customization options. By following the installation steps, you can quickly set up and utilize this package to enhance the user experience of your Next.js app.